Max ByLoading saved progress…

Max By

Implement maxBy(array, iteratee) — find the element of array that produces the largest value when run through iteratee, and return that element, not the value. Think of picking the tallest person in a room: you measure each person's height, but the answer you hand back is the person, not the number on the tape. This mirrors Lodash's _.maxBy: the iteratee can be a function you call on each element, or a property-name string as shorthand for "rank by this field."

Signature

// array:    T[]            — the elements to rank.
// iteratee: ((el: T) => V) — a function returning the value to compare, OR
//         | string         — a property name; shorthand for el => el[name].
// returns:  T | undefined
//   The ELEMENT whose iteratee value is the largest, or undefined if
//   the array is empty.
function maxBy(array, iteratee): T | undefined;

Examples

// Function iteratee: rank objects by their n field.
maxBy([{ n: 1 }, { n: 3 }, { n: 2 }], (o) => o.n);
// → { n: 3 }   (the element, not the 3)
// Property-name iteratee, and a tie. Both 2.1 and 2.9 floor to 2;
// the FIRST element that reached the max wins.
maxBy([{ n: 1 }, { n: 3 }], 'n');     // → { n: 3 }
maxBy([2.1, 1.4, 2.9], Math.floor);   // → 2.1

Notes

  • Return the element, not the score. The iteratee decides who wins by producing a comparable value, but you hand back the original element. maxBy([{ n: 3 }], 'n') returns { n: 3 }, never 3.
  • The iteratee has two forms. A function is called on each element. A string is a property name — maxBy(items, 'n') behaves like maxBy(items, (x) => x.n).
  • Ties keep the first. If two elements produce the same maximum value, return the one that appeared earlier in the array.
  • Empty array returns undefined. There is no element to return.
  • Preserve identity. For object elements, return the exact same reference that was passed in, not a copy.
  • Don't mutate the input. Read each element once; return one of them.
Loading editor…