JavaScript: Array.prototype.reduce

By Xah Lee. Date: . Last updated: .
arrayX.reduce(f)
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.

If array is empty, it's an error. Give initValue to avoid error.

arrayX.reduce(f, initValue)
Start with f(initValue, first_array_item)

For example: sum can be computed by

// Sum of array
console.log( [1,2,3].reduce((x,y) => x+y) === 6 ); // true
// TypeError: Reduce of empty array with no initial value
console.log(
 [].reduce((x,y) => x+y)
);

// fix
console.log(
 [].reduce((x,y) => x+y, 0)
);

Examples

const aa = ["a", "b", "c", "d"];

// a function that join 2 strings
const ff = ((x, y) => {
    console.log( x, y );
    return x + y; }
);

console.log(
 aa.reduce(ff)
); // abcd


// prints

// a b
// ab c
// abc d
// abcd
// example of using reduce with second arg
const xx = [1,2,3];
const ff = ((x,y) => x+y);
console.log( xx.reduce (ff, 10) === 16 ); // true

Reduce from Right Side

Array.prototype.reduceRight

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype