Skip to content

diff

Returns a new array containing elements from the first array that are not present in the second. For arrays of objects, pass an iteratee function to derive an identity value used for comparison.

import { diff } from "1o1-utils";
import { diff } from "1o1-utils/diff";
function diff<T>({ array, values, iteratee }: DiffParams<T>): T[]
NameTypeRequiredDescription
arrayT[]YesThe source array to filter
valuesT[]YesThe values to exclude from the source array
iteratee(item: T) => unknownNoFunction returning the identity value used to compare

T[] — A new array containing elements from array not present in values.

diff({ array: [1, 2, 3, 4], values: [2, 4] });
// => [1, 3]
diff({
array: [{ id: 1 }, { id: 2 }, { id: 3 }],
values: [{ id: 2 }],
iteratee: (item) => item.id,
});
// => [{ id: 1 }, { id: 3 }]
  • Throws if array is not an array.
  • Throws if values is not an array.
  • Without iteratee, items are compared with SameValueZero (Set semantics) — NaN equals NaN, +0 equals -0.
  • With iteratee, mapped values are compared with the same SameValueZero semantics; the function is called for every element of both arrays.
  • Errors thrown by iteratee propagate to the caller.
  • Order of array is preserved.
  • Duplicates in array that are not in values are kept.
  • Inputs are not mutated.

difference, except, exclude, subtract arrays, set difference

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use diff to remove a list of items from an array of objects by id.