Skip to content

Instantly share code, notes, and snippets.

@krstffr
Created December 7, 2016 12:59
Show Gist options
  • Save krstffr/9aaee903a37d8dc608bacd43267216ba to your computer and use it in GitHub Desktop.
Save krstffr/9aaee903a37d8dc608bacd43267216ba to your computer and use it in GitHub Desktop.
Find element based on highest property value (Javascript)
// Let's say you have a collection like this one:
// [{ name: 'Kristoffer', IQ: 120 }, { name: 'Steve', IQ: 88 }, { name: 'Jim', IQ: 142 }]
// And you want to get the person with the highest IQ. It's very simple. You can just do this:
const findElementByHighestKey = (collection, key) =>
collection.reduce((memo, el) => el[key] > memo[key] ? el : memo, { [key]: 0 });
// A version with somem more safety (empty array? No problem!)
const findElementByHighestKey = (collection, key) =>
// Make sure we have a collection with items and a key…
!collection || !key || collection.length < 1
// …if we don't: return an empty array.
? []
// Else just do the good stuff!
: collection.reduce((memo, el) => el[key] > memo[key] ? el : memo, { [key]: 0 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment