Last active
September 3, 2019 01:38
-
-
Save dottedsquirrel/c7cf5949dc8cbc8b8d33f0f57eeb8d6f to your computer and use it in GitHub Desktop.
JavaScript array reduce() example 2
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
let animals = [ | |
{name: 'Tibbers', type: 'cat', isNeutered: true, age: 2}, | |
{name: 'Fluffball', type: 'rabbit', isNeutered: false, age: 1}, | |
{name: 'Strawhat', type: 'cat', isNeutered: true, age: 5} | |
] | |
// How old are all the animals combined? | |
// 0 is the starting value and acts as the first acculmulator value | |
// will return 8 | |
let totalAge = animals.reduce((acculmulator, animal) => { | |
return acculmulator + animal.age; | |
}, 0); | |
// lets say you want to find out the oldest animal | |
// code below will return {name: 'Strawhat', type: 'cat', isNeutered: true, age: 5} | |
let oldestPet = animals.reduce((oldest, animal) => { | |
return (oldest.age || 0) > animal.age ? oldest : animal; | |
}, {}); | |
// decrypting the code above and how terniaries work | |
// the condition --> (oldest.age || 0) > animal.age | |
// if true --> ? oldest | |
// else --> : animal | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment