Streaming on Twitch twice a week

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`
  { name: 'Leela',  age: 31   },
  { name: 'Fry',    age: 1031 },
  { name: 'Hubert', age: 165  },
  { name: 'Bender', age: 10   }
], 'age')
// ⇒ { name: 'Fry', age: 1031 }

More fire tips

Namespacing styled-components

To improve the readability of React components, we can import the styled-components they use from another file under a ui-namespace.

Read fire tip

Read all fire tips →