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

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

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

For example: sum can be written as myArray.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) { return x + y; }

); // 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 2015 §Indexed Collections#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: What's Array-Like Object?
  6. JavaScript: How to Convert Array-Like Object to Array?
  7. 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.