In JavaScript, the Array.prototype.reduce()
and Array.prototype.reduceRight()
methods only differ in terms of how they traverse elements of an array:
Array.prototype.reduce()
starts from left-to-right;Array.prototype.reduceRight()
starts from right-to-left.
Other than that, there are no differences between the two; they both apply the given function against an accumulator and each value of the array, to reduce it to a single value.
Consider the following example, which illustrates the difference between the two:
const arr = ['a', 'b', 'c', 'd']; const ltr = arr.reduce((previous, current) => previous + current); const rtl = arr.reduceRight((previous, current) => previous + current); console.log(ltr); // 'abcd' console.log(rtl); // 'dcba'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.