JS: Array.prototype.reduce

By Xah Lee. Date: . Last updated: .
arrayX.reduce(f)
Recurse a function of 2 parameters, each time feed it the last result and new item in array, till no more items. Return the result.

For example:

  • [1,2].reduce(f) → f(1,2)
  • [1,2,3].reduce(f) → f(f(1,2),3)
  • [1,2,3,4].reduce(f) → f(f(f(1,2),3),4)
const xx = ["1", "2", "3", "4"];
console.log(xx.reduce((x, y) => x + y) === "1234");

The function f is passed 4 args:

  1. The previous result
  2. The current array item
  3. The current array index (optional)
  4. The object being traversed (optional)

The function f should return one value.

  • If array is empty, it's an error. Give initValue to avoid error.
  • If array only has only one item, that item or the init value is returned.
arrayX.reduce(f, initValue)
Start with f(initValue, first_array_item)
const xx = ["1", "2", "3", "4"];
console.log(xx.reduce((x, y) => x + y, "0") === "01234");

example, sum can be computed by

// Sum of array
console.log([1, 2, 3].reduce((x, y) => x + y) === 6);
// empty array, is error
console.log( [].reduce((x,y) => x+y) );
// TypeError: Reduce of empty array with no initial value
// empty array, with init value. return init value
console.log([].reduce((x, y) => x + y, 1) === 1);
// array with just 1 element. return that element
console.log(
  [1].reduce((x, y) => x + y) === 1,
);

JavaScript, Array Reduce, Fold

BUY ΣJS JavaScript in Depth