Skip to content

Instantly share code, notes, and snippets.

@hzhu
Last active May 2, 2019 14:15
Show Gist options
  • Save hzhu/7cd639f045a755dfaf3f to your computer and use it in GitHub Desktop.
Save hzhu/7cd639f045a755dfaf3f to your computer and use it in GitHub Desktop.
Reduce ES5 / ES6
// reduce boils down a list of values into a single value
// var callback = function (previousValue, currentValue, index, array) {
// return previousValue + currentValue
// }
// [].reduce(callback, initialValue)
//
// Reduce invokes the callback on each item in the array.
// On the first invocation, the first item is passed to the callback as currentValue.
// and the initialValue is passed as the previousValue.
// The returned value of that is then passed into the next invocation of the second item as previousValue.
// And the currentValue will be the second item.
//
//
let items = [["Henry", "Angus Burger", "Water", 13.95, 0.00],
["Maggie", "New York Steak", "Diet Coke", 29.95, 1.99],
["Anna", "Grilled Salmon", "Water", 17.99, 0.00],
["Haylie", "Mac & Cheese", "Orange Juice", 4.95, .99]];
let outputES6 = items.reduce((orders, line) => {
orders[line[0]] = { entree: line[1],
drink: line[2],
total: line[3] + line[4] }
return orders;
}, {});
var outputES5 = items.reduce(function (orders, line) {
orders[line[0]] = { entree: line[1],
drink: line[2],
total: line[3] + line[4] }
return orders;
}, {});
console.log(outputES6)
console.log(outputES5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment