Skip to content

maxBy

Returns the element of an array with the greatest derived key, computed by keyFn. Unlike max, which only compares raw numbers, maxBy returns the item itself, not the key. On a tie, the earliest element with that key wins. null and undefined are treated as empty arrays and return undefined.

Available since v3.0.8

import { maxBy } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { maxBy } from 'helpers4/array';
maxBy<T>(array: readonly T[] | null | undefined, keyFn: function): T | undefined
ParameterTypeDescription
arrayreadonly T[] | null | undefinedArray of items
keyFnfunctionDerives the comparable key for an item

T | undefined — The element with the greatest key, or undefined for empty arrays, null, undefined

Pick the item with the greatest derived value

Section titled “Pick the item with the greatest derived value”

Unlike max(), maxBy() returns the whole item, chosen by a key derived from it.

maxBy(
  [{ name: 'a', size: 3 }, { name: 'b', size: 9 }, { name: 'c', size: 1 }],
  (item) => item.size,
)
// => { name: 'b', size: 9 }

There is no maximum to return for an empty array.

maxBy([], (item: { size: number }) => item.size)
// => undefined

View source on GitHub