minBy
Finds the element that yields the minimum value when the iteratee function is applied to each element of the array.
- If multiple elements share the minimum value, the first one is returned.
- Returns
undefinedif the array is empty. - If the
iterateereturnsNaNfor an element, that element is returned immediately. (like built-inMath.min,NaNtakes precedence) - When a non-empty tuple type (
readonly [T, ...T[]]) is passed, the return type is inferred asT.
Code
Interface
typescript
function minBy<T>(
items: readonly [T, ...T[]],
iteratee: (element: T, index: number, array: T[] | readonly T[]) => number
): T;
function minBy<T>(
items: readonly T[],
iteratee: (element: T, index: number, array: T[] | readonly T[]) => number
): T | undefined;
Usage
typescript
import { minBy } from '@modern-kit/utils';
minBy([{ a: 1 }, { a: 2 }, { a: 3 }], (x) => x.a); // { a: 1 }
minBy([] as { a: number }[], (x) => x.a); // undefined
minBy([3, NaN, 1], (x) => x); // NaN
minBy(
[
{ name: 'john', age: 30 },
{ name: 'jane', age: 28 },
{ name: 'joe', age: 26 },
],
(x) => x.age
); // { name: 'joe', age: 26 }