Skip to content

minBy

Edit

Finds the first item with the smallest finite derived number.

minBy.ts
export type MinBySelector<Value> = (
this: void,
value: Value,
index: number,
array: readonly (Value | undefined)[],
) => number;
/** Returns the first value with the smallest finite derived number. */
export const minBy = <const T>(
array: readonly T[],
getValue: MinBySelector<T>,
): T | undefined => {
let result: T | undefined;
let minimum = Infinity;
let hasResult = false;
for (let index = 0; index < array.length; index += 1) {
if (!Object.hasOwn(array, index)) continue;
const value = array[index] as T;
const candidate = getValue(value, index, array);
if (!Number.isFinite(candidate)) continue;
if (!hasResult || candidate < minimum) {
result = value;
minimum = candidate;
hasResult = true;
}
}
return result;
};
Terminal
wget -O src/lib/minBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/minBy.ts
minBy.example.ts
import { minBy } from "./minBy";
const cheapest = minBy(
[{ name: "A", price: 20 }, { name: "B", price: 12 }],
(item) => item.price
);
  • array (readonly T[]) — Candidate values. Empty slots are skipped.
  • getValue ((value: T, index, array: readonly (T | undefined)[]) => number) — Produces comparable numbers and is invoked without a receiver. value is always present; the original array retains skipped holes.
  • Returns T | undefined; non-finite results are ignored.