Getting the array element with the largest given property

We can get the largest number from an array of numbers with Math.max(), but that does not work with objects. If we have an array of objects, we can get the element with the largest value of a given property like this:

// takes an array and the name of a property to compare by
const maxBy = (array, prop) => {
  return array.reduce((max, element) => element[prop] > max[prop] ? element : max)
}

// find the object with the largest `age`
maxBy([
  { name: 'Leela',  age: 31   },
  { name: 'Fry',    age: 1031 },
  { name: 'Hubert', age: 165  },
  { name: 'Bender', age: 10   }
], 'age')
// ⇒ { name: 'Fry', age: 1031 }

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.