Skip to content

differenceBy

Edit

Returns values whose derived keys do not occur in the comparison arrays.

differenceBy.ts
export type DifferenceBySelector<Source, Comparison, Key> = (
this: void,
value: Source | Comparison,
index: number,
array: readonly (Source | Comparison | undefined)[],
) => Key;
/** Returns values whose derived keys are absent from every other array. */
export const differenceBy = <const Source, Key, const Comparison = Source>(
array: readonly Source[],
others: ReadonlyArray<readonly Comparison[]>,
getKey: DifferenceBySelector<Source, Comparison, Key>,
): Source[] => {
const excluded = new Set<Key>();
for (let otherIndex = 0; otherIndex < others.length; otherIndex += 1) {
if (!Object.hasOwn(others, otherIndex)) continue;
const other = others[otherIndex];
if (!Array.isArray(other)) {
throw new TypeError("others must contain only arrays");
}
for (let index = 0; index < other.length; index += 1) {
if (!Object.hasOwn(other, index)) continue;
excluded.add(getKey(other[index] as Comparison, index, other));
}
}
const result: Source[] = [];
for (let index = 0; index < array.length; index += 1) {
if (!Object.hasOwn(array, index)) continue;
const value = array[index] as Source;
if (!excluded.has(getKey(value, index, array))) result.push(value);
}
return result;
};
Terminal
wget -O src/lib/differenceBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/differenceBy.ts
differenceBy.example.ts
import { differenceBy } from "./differenceBy";
const remaining = differenceBy(
[{ id: 1 }, { id: 2 }],
[[{ id: 2 }]],
(item) => item.id
);
  • array (readonly Source[]) — Values to filter. Empty slots are skipped.
  • others (readonly (readonly Comparison[])[]) — Arrays containing excluded keys. Empty slots in the list or its arrays are skipped.
  • getKey ((value: Source | Comparison, index, array: readonly (Source | Comparison | undefined)[]) => Key) — Produces the comparison key and is invoked without a receiver. value is always present; the current source or comparison array retains skipped holes, so reading one can produce undefined.

Returns Source[]; comparison values do not widen the result type.