reduce function
Count the number of times a value of a particular type in an object exists
Search for a command to run...
Count the number of times a value of a particular type in an object exists
No comments yet. Be the first to comment.
index.html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Workers</title> <script src="main.js"></script> </head> <body> 1 USD = <span...
Fetch the latest currency conversion rate using async ... await
Taking advantage of latest JavaScript features: ECMAScript 2024

Replacing deprecated event.target.selectedIndex with this.selectedIndex

Using destructuring to update an object's attribute

JavaScript
12 posts
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