keyBy
EditIndexes array values by a derived property key.
export type KeyByKeySelector<Value, Key extends PropertyKey> = ( this: void, value: Value, index: number) => Key;
/** * Indexed values are optional because a selector may not produce every key in * its return type for a particular input. */export type KeyByResult<Value, Key extends PropertyKey> = Partial< Record<Key, Value>>;
/** Indexes values by a derived property key, with later values replacing earlier ones. */export const keyBy = <Value, Key extends PropertyKey>( array: readonly Value[], getKey: KeyByKeySelector<Value, Key>): KeyByResult<Value, Key> => { const result = Object.create(null) as KeyByResult<Value, Key>; for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) continue; const value = array[index] as Value; Reflect.set(result, getKey(value, index), value); } return result;};Download
Section titled “Download”wget -O src/lib/keyBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/keyBy.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/keyBy.ts" src/lib/keyBy.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { keyBy } from "./keyBy";
const usersById = keyBy( [{ id: "ada", active: true }, { id: "lin", active: false }], (user) => user.id);
const ada = usersById.ada;// { id: "ada", active: true } | undefinedarray(readonly T[]) — Values to index. Empty slots are skipped.getKey(KeyByKeySelector<T, Key>) — Produces each object key and is invoked without a receiver.- Returns
Partial<Record<Key, T>>with a null prototype. A value isundefinedwhen its key was not produced. - Later duplicate keys replace earlier values.