Min ByLoading saved progress…

Min By

Implement minBy(array, iteratee) — scan an array and return the single element that produces the smallest value when run through iteratee. The catch worth saying out loud: you return the element itself, not the number it mapped to. If you have a list of people and want the youngest, minBy hands you back the whole person, not their age. This mirrors Lodash's _.minBy: 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 search.
// iteratee: ((el: T) => number)  — 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 smallest. undefined if the array is empty.
function minBy(array, iteratee): T | undefined;

Examples

// Function iteratee: smallest by the `n` field. Returns the OBJECT, not 1.
minBy([{ n: 3 }, { n: 1 }, { n: 2 }], (o) => o.n);
// → { n: 1 }
// Property-name iteratee: rank by the named field.
minBy([{ n: 3 }, { n: 1 }], 'n');
// → { n: 1 }

// Ties keep the FIRST element that produced the minimum.
minBy([2.6, 1.4, 1.9], Math.floor);
// → 1.4   (2.6→2, 1.4→1, 1.9→1; 1.4 reaches the min of 1 first)

Notes

  • Return the element, not the value. The smallest mapped value might be 1, but the answer is the element that produced it — keep the element and its mapped value together as you scan.
  • The iteratee has two forms. A function is called on each element; a string is a property name, so minBy(items, 'age') behaves like minBy(items, (x) => x.age).
  • Ties go to the first. When two elements map to the same minimum, return the one that appeared earlier in the array.
  • Empty array returns undefined. There is no element to return.
  • Don't mutate the input. Read each element once; don't sort or splice the array.
Loading editor…