Last active
March 11, 2019 18:34
-
-
Save RedGhoul/9bd80e04f031a85ef6214d735138be96 to your computer and use it in GitHub Desktop.
ReduceInJS
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
// Here we have a list of all the transactions made by Mike | |
const transActionsForMike = [ {Name: "Bike", Cost: 5000}, | |
{Name: "Apple Music", Cost: 20}, | |
{Name: "Cook Book", Cost: 30}, | |
{Name: "Azure Hosting", Cost: 60}, | |
{Name: "Phone Bill", Cost: 70}]; | |
// And we try to figure out how much Mike Spent | |
// "reduce" takes in three main arguments, the Accumulator (acc), the | |
// currentValue (curr) in the form of an anonymous function. And a inital | |
// value for the accumulator (in our example its 0). The accumulator acts | |
// like a bucket that you keep adding things to. Or keep modifying every | |
// interaction of the reduce function. | |
// Here we are taking each object in the "transActionsForMike" variable. Then | |
// we are accessing the cost property of each object, then continuously adding it to | |
// the accumulator. | |
// then at the very end we are returning the accumulator that gets dumped into the | |
// MikesSpending variable. | |
let MikesSpending = transActionsForMike.reduce((acc, curr) =>{ | |
return acc + curr.Cost; | |
}, 0); | |
console.log(MikesSpending) // MikesSpending is: 5180 | |
// Note you can make the accumulator into anything you want. That is, you can set the | |
// inital property of the accumulator to object or array and continously add things | |
// to it, to have the desired output. | |
// Other things that you can have "reduce" pass into your function is: | |
// accumulator, currentValue, currentIndex, array (yes the whole array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment