Created
May 12, 2016 13:40
-
-
Save benwells/0111163b3cccfad0804d994c70de7aa1 to your computer and use it in GitHub Desktop.
Using Array.reduce to sum a property in an array of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Thanks - super useful!
Is it possible to use reduce if I have a calculation trough-out multiple properties like this:
var items = [ { name: 'Item 1', amount: 123, discount: 0.1 }, { name: 'Item 2', amount: 22, discount: 0.1 }, { name: 'Item 3', amount: 16, discount: 0.2 }, { name: 'Item 4', amount: 300, discount: 0 } ];
So I have to do something like this:
total = sum_all_items(amount - (amount * discount))
simplify it as total = sum_all_items(amount * (1 - discount))
OR
first, just make, discount = 1 - discount, and then, sum(amount * discount)
Banging. Nice one, mate.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks dude!