JavaScript Arrays: Reduce Right
Welcome to the Reduce Right lesson!
JavaScript arrays' `.reduceRight` method is like `.reduce`, except that it begins from the right of the array, at the last element, and moves left.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
.reduceprocesses array items from left to right. There's also a less-common variant called.reduceRight. With.reduceRight, the array is processed from right to left.This doesn't matter for many operations, like summing numbers. We get the same sum whether we do
1 + 20 + 300or300 + 20 + 1.>
[1, 20, 300].reduce((acc, current) => acc + current);Result:
321
>
[1, 20, 300].reduceRight((acc, current) => acc + current);Result:
321
However,
.reduceRightproduces a different result when the order of operations matters. In the next example, we concatenate (join) strings in reverse order..reduceRightbegins at the right ('c') and ends at the left ('a').>
['a', 'b', 'c'].reduceRight((acc, current) => acc + current);Result:
'cba'
Left vs. right is also important for subtraction.
.reduceand.reduceRightdiffer here because20 - 1 != 1 - 20.>
[20, 1].reduce((acc, current) => acc - current);Result:
19
>
[20, 1].reduceRight((acc, current) => acc - current);Result:
-19
When the order of operations matters, remember that
.reduceRightis available!