JS: Array.prototype.reduce

By Xah Lee. Date: . Last updated: .

If we have the array [1,2,3,4],

[1,2,3,4].reduce ( f )

Returns

f(f(f(1,2),3),4)

In general reduce first computes f(x,y) where x and y are first 2 items in array. Then, recursively apply f, taking a new array element as second argument, until the last item in array is used, and returns the result.

If firstValue is given, is used as the first value to begin. That is, start with f(firstValue, first_array_item)

The function f is passed 4 args:

  1. the previousValue (value from the previous call to f)
  2. the currentValue (value of the current element)
  3. the currentIndex
  4. the object being traversed.

The function f should return 1 value.

For example: sum can be computed by

[1,2,3].reduce(function (x,y) {return x+y;})

// example of using reduce

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. Sum of array

console.log(
    [1,2,3].reduce( function (x,y) {return x+y;} )
); // 6
// example of using reduce with second arg

const xx = [1,2,3];

const ff = function (x,y) {return x+y;}

console.log(
  xx.reduce (ff, 10)
); // 16

reduce does not directly mutate the object on which it is called but the object may be mutated by the calls to f.

The range of elements processed by reduce is set before the first call to f. Elements that are appended to the array after the call to reduce begins will not be visited by f. If existing elements of the array are changed, their value as passed to f will be the value at the time reduce visits them; elements that are deleted after the call to reduce begins and before being visited are not visited.

reduceRight

See also:

JS: Array.prototype.reduceRight

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.reduce

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon