Working with JavaScript Arrays, Part 3: Array.prototype.reduce

2015-12-06 00:00:00 by Mike

In the final article of a three part series dealing with JavaScript arrays, we review the Array.prototype.reduce() function.
(The first two articles can be found here: Part 1 and Part 2)

Array.prototype.reduce(), added in ECMAScript 5.1, is useful for efficiently aggregating values based on array element properties.
The callback structure of reduce() provides a callback function that has access to an array, and is regarded as more elegant than a traditional JavaScript 'for' loop.

Here is an example of Array.prototype.reduce():

Array.prototype.reduce()

Purpose: Returns an aggregate value corresponding to elements in the input array.

Input:

var topSellers = [{
'title': 'The Mythical Man Month',
'units': 3791
},
{
'title': 'The Mythical Man Month',
'units': 2703
},
{
'title': 'Eloquent JavaScript',
'units': 2889
},
{
'title': 'JavaScript: The Good Parts',
'units': 3016
},
{
'title': 'Secrets of the JavaScript Ninja',
'units': 4082
}];

Example Usage:

var totalUnits = topSellers.reduce(function(previousValue, element) {
return previousValue + element.units;
}, 0);

Results:

Total units: 16481