user200783
user200783

Reputation: 14346

Is `Array.prototype.reduceRight` identical to `reverse` followed by `reduce`?

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

Answers (3)

str
str

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

qiAlex
qiAlex

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

VLAZ
VLAZ

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

Related Questions