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

); // 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

var xx = [1,2,3];

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

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

See also: JavaScript: Array.prototype.reduceRight


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

Array Topic

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

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.