Skip to content

Instantly share code, notes, and snippets.

@thefonso
Last active June 10, 2022 17:09
Show Gist options
  • Save thefonso/0f2eadc97ee4a8babbbb2acdeb17c171 to your computer and use it in GitHub Desktop.
Save thefonso/0f2eadc97ee4a8babbbb2acdeb17c171 to your computer and use it in GitHub Desktop.
Reduce line break down for student
// Run as "node reduce.js"
// the same function is repeated in different form below
// understand how each version of the function below works
//
// NOTE: .max and the spread opperator ...
//
// https://www.w3schools.com/jsref/jsref_max.asp
const flips = [
{id:250},
{id:400},
{id:100},
{id:325}
]
// for loop version
let lastFlipId = 0;
let newArray = [];
for(let i = 0; i < flips.length; i++){
//compare
newArray.push(flips[i].id)
lastFlipId = Math.max(...newArray)
}
// .max returns largest number
// ... spreads out values
// we re-write this below as...
// Math.max(largestID, flip.id)
// NOTE: largesId is set to 0
// reduce version
let lastFlipId01 = flips.reduce(function(largestId, flip){
return Math.max(largestId, flip.id)
},0);
// arrow function version
let lastFlipId02 = flips.reduce((maxId, flip) => Math.max(maxId, flip.id), 0)
// renamed vars for readability
let lastFlipId03 = flips.reduce((largestId, flip) => Math.max(largestId, flip.id), 0)
console.log(lastFlipId)
console.log(lastFlipId01)
console.log(lastFlipId02)
console.log(lastFlipId03)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment