Skip to content

uniqueBy

Edit

Keeps the first value for each distinct derived key.

uniqueBy.ts
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;
};
Terminal
wget -O src/lib/uniqueBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/uniqueBy.ts
uniqueBy.example.ts
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. value is always present; the original array retains skipped holes.
  • Returns a new T[] in first-seen order.