How to use Array reduce() with objects

In my javascript code occasionally I have to loop through an array of objects, and keep a running total of one of their properties. Imagine having an array of objects such as:

var items = [{
  name: 'Shirt',
  count: 10
  name: 'Jumper',
  count: 12

And you want to have a total sum of the objects count. Now you could do this with a for loop:

var total = 0;
for(var i = 0; i < items.length; i++) {
  total += items[i].count;

But in fact, the reduce function in Array.prototype can do most of this legwork for you. The function call takes a callback function as the first parameter, which is executed with a few parameters, but the most important being the first two: the current reduced value, and the next item in the array to apply to that reduced value. The second reduce function parameter is an initial value; great when working with objects. So here’s a quick sum using reduce:

var total = items.reduce(function(value, item) { return value += item.count; }, 0);

To recap, total is assigned to the items array being reduced to a single value which is the sum of all the count properties in each object in the array. We start the count at zero else the very first time the anonymous inner function is executed, the value parameter would be the first object, not the number zero, and would essentially break the sum. Because I work in ES6, the code for me looks like this:

let total = items.reduce((value, item) => value += item.count, 0);

Which looks even neater. Take a look at the Mozilla developer documentation and this very useful Stack Overflow question to learn all you need to have reduce power your JavaScript code.