Array Methods: reduce()

By: Dusty Arlia
Published on Friday, February 21, 2014, 12:25 PM
Last Updated on Tuesday, July 14, 2015 at 4:51 PM
Total Updates: 2

The reduce() method combines or compares all the elements of an array to return a single value. For example:

var my_numbers = [1, 2, 3];
var sum = my_numbers.reduce(function(x,y) {return x+y}, 0);

reduce() takes to arguments:

1 - A function that performs the reduction. This is done by passing two values (two elements) to the function, but returning a single value.

2 - An optional initial value to pass to the function.