Skip to content

Instantly share code, notes, and snippets.

@dottedsquirrel
Last active September 3, 2019 01:38
Show Gist options
  • Save dottedsquirrel/c7cf5949dc8cbc8b8d33f0f57eeb8d6f to your computer and use it in GitHub Desktop.
Save dottedsquirrel/c7cf5949dc8cbc8b8d33f0f57eeb8d6f to your computer and use it in GitHub Desktop.
JavaScript array reduce() example 2
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