Skip to content

Instantly share code, notes, and snippets.

@osorionicolas
Last active January 24, 2022 17:50
Show Gist options
  • Select an option

  • Save osorionicolas/7827b14fd1234397884171e34f016a0c to your computer and use it in GitHub Desktop.

Select an option

Save osorionicolas/7827b14fd1234397884171e34f016a0c to your computer and use it in GitHub Desktop.
Find maximum item of an Array by given key
const people = [
{ name: 'Naruto', age: 24 },
{ name: 'Sasuke', age: 32 },
{ name: 'Minato', age: 42 },
{ name: 'Kakashi', age: 36 }
]
const maxBy = (arr, key) => arr.reduce((max,obj) => {
return max[key] >= obj[key] ? max : obj)
}, {})
maxBy(people, 'age')
// output: { name: 'Minato', age: 42 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment