Skip to content

difference

Edit

Returns values from the first array that do not occur in the comparison arrays.

difference.ts
/** Returns values from the first array that are absent from every other array. */
export const difference = <const T>(
array: readonly T[],
...others: ReadonlyArray<readonly unknown[]>
): T[] => {
const excluded = new Set<unknown>();
for (const other of others) {
if (!Array.isArray(other)) {
throw new TypeError("comparison values must be arrays");
}
for (let index = 0; index < other.length; index += 1) {
if (Object.hasOwn(other, index)) excluded.add(other[index]);
}
}
const result: T[] = [];
for (let index = 0; index < array.length; index += 1) {
if (!Object.hasOwn(array, index)) continue;
const value = array[index] as T;
if (!excluded.has(value)) result.push(value);
}
return result;
};
Terminal
wget -O src/lib/difference.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/difference.ts
difference.example.ts
import { difference } from "./difference";
const available = difference(["read", "write", "delete"], ["delete"]);
// ["read", "write"]
  • array (readonly T[]) — Values to filter. Empty slots are skipped.
  • ...others (readonly (readonly unknown[])[]) — Arrays containing excluded values. Empty slots are skipped, not treated as undefined, and their element types do not widen the result.
  • Returns a new T[] and preserves duplicates from the first array.