Skip to content

Instantly share code, notes, and snippets.

@iamanas20
Forked from benwells/reduce-example.js
Created January 10, 2020 22:35
Show Gist options
  • Save iamanas20/576d0a421a508cc7e51bdc0033cd07be to your computer and use it in GitHub Desktop.
Save iamanas20/576d0a421a508cc7e51bdc0033cd07be to your computer and use it in GitHub Desktop.
Using Array.reduce to sum a property in an array of objects
var accounts = [
{ name: 'James Brown', msgCount: 123 },
{ name: 'Stevie Wonder', msgCount: 22 },
{ name: 'Sly Stone', msgCount: 16 },
{ name: 'Otis Redding', msgCount: 300 } // Otis has the most messages
];
// get sum of msgCount prop across all objects in array
var msgTotal = accounts.reduce(function(prev, cur) {
return prev + cur.msgCount;
}, 0);
console.log('Total Messages:', msgTotal); // Total Messages: 461
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment