maxBy
EditFinds the first item with the largest finite derived number.
export type MaxBySelector<Value> = ( this: void, value: Value, index: number, array: readonly (Value | undefined)[],) => number;
/** Returns the first value with the largest finite derived number. */export const maxBy = <const T>( array: readonly T[], getValue: MaxBySelector<T>,): T | undefined => { let result: T | undefined; let maximum = -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 > maximum) { result = value; maximum = candidate; hasResult = true; } } return result;};Download
Section titled “Download”wget -O src/lib/maxBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/maxBy.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/maxBy.ts" src/lib/maxBy.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { maxBy } from "./maxBy";
const highest = maxBy( [{ name: "A", score: 8 }, { name: "B", score: 10 }], (item) => item.score);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.valueis always present; the original array retains skipped holes.- Returns
T | undefined; non-finite results are ignored.