reduce function
Count the number of times a value of a particular type in an object exists
I hope this code on how to understand the reduce
function in JavaScript is is self-explanatory.
var desks = [
{ type: 'sitting' },
{ type: 'standing' },
{ type: 'sitting' },
{ type: 'sitting' },
{ type: 'standing' }
];
var deskTypes = desks.reduce(function(d, desk)
{
d[desk.type]++;
return d;
}, { sitting: 0, standing: 0 });
console.log(deskTypes);
We are initializing deskTypes to { sitting: 0, standing: 0 }
just before going through the reduce function.
d
gets returned in the function which gets updated to deskTypes
while desk
is each value of desks
in the loop.
node trips.js
{ sitting: 3, standing: 2 }
This works in IE9-IE11 too.
UPDATE : Another common use-case for reduce
:
let shoes = [
{ id:205, name:'reebok', price:50 },
{ id:206, name:'adidas', price:45 },
{ id:207, name:'nike', price:150 },
{ id:208, name:'clarks', price:95 },
{ id:209, name:'bata', price:30 },
];
console.log(shoes.reduce((n, {price}) => n + price, 0));
Will output 370 because 50+45+150+95+30=370