JavaScript: Array.prototype.reduce

By Xah Lee. Date: . Last updated: .
First computes f(x,y) where x and y are first 2 items in array, then apply f, taking a new array element as second argument, repeat, until all items in array are used, return result. For example, [1,2,3,4].reduce(f) returns f(f(f(1,2),3),4).

The function f is passed 4 args:

  1. The previousResult
  2. The currentValue
  3. The currentIndex
  4. The object being traversed.

The function f should return 1 value.

const aa = ["a", "b", "c", "d"];
console.log(aa.reduce((x, y) => x + y) === "abcd");
  • If array is empty, it's an error. Give initValue to avoid error.
  • If array only has 1 item, that item or the init value is returned.
arrayX.reduce(f, initValue)
Start with f(initValue, first_array_item)
const aa = ["a", "b", "c", "d"];
console.log(aa.reduce((x, y) => x + y, "0") === "0abcd");

For 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

JavaScript in Depth

JS Obj Reference