reduceRight method
The reduceRight
method works exactly
like reduce
- see it for a complete understanding. The
only difference is that reduce
iterates
from left to right, while reduceRight
iterates from right to left.
Syntax
array.reduceRight(function(intermediate result, element, index, array) {
return new intermediate result;
}, initial value);
Example
Let's find the sum of the array elements:
let arr = [1, 2, 3, 4, 5, 6];
let res = arr.reduceRight(function(sum, elem) {
return sum + elem;
}, 0);
console.log(res);
The code execution result:
21
Example
Let's merge a two-dimensional array into a one-dimensional:
let arr = [['a', 'b'], ['c'], ['d', 'e']];
let res = arr.reduceRight(function(elem1, elem2) {
return elem1.concat(elem2);
}, []);
console.log(res);
The code execution result:
['d', 'e', 'c', 'a', 'b']