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

javascriptarray.reduceRight(function(intermediate result, element, index, array) {
  return new intermediate result;
}, initial value);

Example

Let's find the sum of the array elements:

javascriptlet 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:

javascript21

Example

Let's merge a two-dimensional array into a one-dimensional:

javascriptlet arr = [['a', 'b'], ['c'], ['d', 'e']];

let res = arr.reduceRight(function(elem1, elem2) {
  return elem1.concat(elem2);
}, []);

console.log(res);

The code execution result:

javascript['d', 'e', 'c', 'a', 'b']

See also

  • the reduce method
    that performs a similar operation
  • the filter method
    that allows you to filter the elements of an array
  • the map and forEach methods
    that allow you to apply a function to each element of an array
  • the some and every methods
    that perform an array check