Reputation: 14346
Array.prototype.reduceRight
reduces an array to a single value, working right-to-left (i.e. starting from the end of the array).
Is calling reduceRight
exactly the same as calling reverse
followed by reduce
? If so, why does reduceRight
exist?
Upvotes: 2
Views: 754
Reputation: 44999
As already mentioned, it is not the same. Here are two more use cases, where those two versions behave differently:
Everything that is based on the index (third argument of the callback function called by both reduce
and reduceRight
) might behave differently.
Reverse loops are often used when the original array is being modified. Depending on the exact use case, that might work with reduceRight
but break with reduce
.
Upvotes: 4
Reputation: 4346
It already was mentioned that .reverse()
modifyes iinitial array,
In addition, according to spec:
https://tc39.es/ecma262/#sec-array.prototype.reduce
https://tc39.es/ecma262/#sec-array.prototype.reduceright
Implementations are a bit different.
Let me allow the analogy with .push()
and .unshift()
- they do also quite a same, inserting an element in array, we use push a lot, and unshift quite rarely, but time to time there are some perfect moments for unshift
as well as for reduceright
Upvotes: 1
Reputation: 29084
Array#reduceRight
is not the same as Array#reverse()
-> Array#reduce()
. Here is the key difference .reduce()
/.reduceRight()
do not modify the starting array:
const arr = ["a", "b", "c"];
const combine = arr.reduceRight((a, b) => a+b, "");
console.log(combine);
console.log(arr);
However, .reverse()
does:
const arr = ["a", "b", "c"];
const combine = arr.reverse().reduce((a, b) => a+b, "");
console.log(combine);
console.log(arr);
There is also question for a performance - .reverse
will incur an additional O(n)
processing to reverse the array in-place, that's on top of the .reduce()
that already operates at O(n)
. Yes, the final complexity is still O(n)
(we ignore the constants) but having a single pass through the array is faster.
Upvotes: 5