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 )



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; }

); // abcd

// prints

// a b
// ab c
// abc d
// abcd
// example of using reduce. Sum of array

    [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;}

  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.


See also:

JS: Array.prototype.reduceRight

JS Array

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

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials