JS: Array.prototype.reduce

By Xah Lee. Date: . Last updated: .

Returns f(f(f(A₀,A₁),A₂),A₃) till Aₙ, where Aᵢ is element of ith index of myArray.

The f should be function that takes 2 values and return 1 value.

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

For example: sum can be written as

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

// example of using reduce

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

// a function that join 2 strings
var ff = function (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

var xx = [1,2,3];

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

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

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
Like what you read? Buy JavaScript in Depth