For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/differenceWith.md.

differenceWith es-toolkit

Computes the difference of two arrays using a custom comparison function and returns a new array.

const result = differenceWith(firstArr, secondArr, areItemsEqual);

Usage

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 }]

Parameters

firstArrT[]required

The base array to compute the difference from.

secondArrU[]required

The array containing elements to exclude from the first array.

areItemsEqual(x: T, y: U) => booleanrequired

The function that determines if two elements are equal.

Returns

A new array containing elements that are determined to exist only in the first array according to the comparison function.

T[]
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.