uniqueBy
EditKeeps the first value for each distinct derived key.
export type UniqueBySelector<Value, Key> = ( this: void, value: Value, index: number, array: readonly (Value | undefined)[],) => Key;
/** Keeps the first value for every distinct derived key. */export const uniqueBy = <const T, Key>( array: readonly T[], getKey: UniqueBySelector<T, Key>,): T[] => { const seen = new Set<Key>(); const result: T[] = []; for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) continue; const value = array[index] as T; const key = getKey(value, index, array); if (seen.has(key)) continue; seen.add(key); result.push(value); } return result;};Download
Section titled “Download”wget -O src/lib/uniqueBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/uniqueBy.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/uniqueBy.ts" src/lib/uniqueBy.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { uniqueBy } from "./uniqueBy";
const users = uniqueBy( [{ id: 1, name: "Ada" }, { id: 1, name: "A." }], (user) => user.id);array(readonly T[]) — Values to deduplicate. Empty slots are skipped.getKey((value: T, index, array: readonly (T | undefined)[]) => Key) — Produces the identity key and is invoked without a receiver.valueis always present; the original array retains skipped holes.- Returns a new
T[]in first-seen order.