Skip to content

Instantly share code, notes, and snippets.

@dnasca
Last active October 30, 2017 23:11
Show Gist options
  • Save dnasca/e25a5541cbcbf6f6181fca6f9e095ea1 to your computer and use it in GitHub Desktop.
Save dnasca/e25a5541cbcbf6f6181fca6f9e095ea1 to your computer and use it in GitHub Desktop.
reduce is awesome
// 3 ways to reduce from an array
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a)
var orders = [
{ amount: 100 },
{ amount: 200 },
{ amount: 300 },
{ amount: 400 },
]
// es5 'for' iteration
var totalAmount = 0
for (var i = 0; i < orders.length; i++) {
totalAmount += orders[i].amount
}
// reduce es5
var totalAmount = orders.reduce(function(sum, order) {
return sum + order.amount
}, 0)
// reduce es6
// easy to understand, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
let totalAmount = orders.reduce((sum, order) => sum + order.amount, 0)
// invoke the function
console.log(totalAmount) // => 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment