JavaScript: Array.prototype.reduce and reduceRight Example

By Xah Lee. Date: . Last updated: .

reduce is a function, and is a property of Array.prototype object.

Syntax:

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

For example: sum can be written as myArray.reduce(function (x,y) {return x+y;}).

ES5 §15#sec-15.4.4.21

// example of using reduce

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

// a function that join 2 strings
var ff = function (x, y) { return x + y; }

console.log(
    aa.reduce(ff)
); // 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

Array.prototype.reduceRight

array.reduceRight(…) → same as reduce() but start from end of array. ES5 §15#sec-15.4.4.22
// example of using reduceRight

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

// a function that join 2 strings
var ff = function (x, y) { return x + y; }

console.log(
    aa.reduceRight(ff)
); // dcba

back to JavaScript: Array Methods

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.