docs/reference/array/differenceWith.md
Computes the difference of two arrays using a custom comparison function and returns a new array.
const result = differenceWith(firstArr, secondArr, areItemsEqual);
differenceWith(firstArr, secondArr, areItemsEqual)Use differenceWith when you want to compute the difference between two arrays using a custom comparison function. It determines if two elements are equal through the comparison function, and returns elements that exist only in the first array.
import { differenceWith } from 'es-toolkit/array';
// Compute the difference based on id in object arrays.
const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
const array2 = [{ id: 2 }, { id: 4 }];
const areItemsEqual = (a, b) => a.id === b.id;
differenceWith(array1, array2, areItemsEqual);
// Returns: [{ id: 1 }, { id: 3 }]
// Elements with id 2 are considered equal and excluded.
// You can compare arrays of different types.
const objects = [{ id: 1 }, { id: 2 }, { id: 3 }];
const numbers = [2, 4];
const areItemsEqual2 = (a, b) => a.id === b;
differenceWith(objects, numbers, areItemsEqual2);
// Returns: [{ id: 1 }, { id: 3 }]
You can compare elements with complex conditions.
import { differenceWith } from 'es-toolkit/array';
const users1 = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 },
];
const users2 = [
{ name: 'Alice', age: 31 }, // Same user even if age is different
{ name: 'David', age: 25 },
];
const areUsersEqual = (a, b) => a.name === b.name;
differenceWith(users1, users2, areUsersEqual);
// Returns: [{ name: 'Bob', age: 25 }, { name: 'Charlie', age: 35 }]
firstArr (T[]): The base array to compute the difference from.secondArr (U[]): The array containing elements to exclude from the first array.areItemsEqual ((x: T, y: U) => boolean): The function that determines if two elements are equal.(T[]): A new array containing elements that are determined to exist only in the first array according to the comparison function.