Skip to content

maxBy

Edit

Finds the first item with the largest finite derived number.

maxBy.ts
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;
};
Terminal
wget -O src/lib/maxBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/maxBy.ts
maxBy.example.ts
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. value is always present; the original array retains skipped holes.
  • Returns T | undefined; non-finite results are ignored.