Created
December 7, 2016 12:59
-
-
Save krstffr/9aaee903a37d8dc608bacd43267216ba to your computer and use it in GitHub Desktop.
Find element based on highest property value (Javascript)
This file contains hidden or 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'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