Getting the array item 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 }
More fire tips
Getting properties from objects that match a condition
Read fire tipSplitting arrays into X elements and “the rest”
When a feature calls for the first five photos from a list and a link that says “27 more photos”, we can split the list of photos into these two blocks.
Read fire tip