Skip to main content

reduce function

Count the number of times a value of a particular type in an object exists

Updated 1 min readMarkdown

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

About the author

  • I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

No comments yet. Be the first to comment.