JavaScript

JavaScript

reduce function

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

Anjanesh Lekshminarayanan's photo
Anjanesh Lekshminarayanan
·Jul 4, 2022·

1 min read

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.

 
Share this