Skip to main content

differenceBy()

differenceBy<T>(array, values, iteratee): T[]

Creates an array of values from the first array that are not present in the second array, using an iteratee to compute the comparison value.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the arrays.


Parametersโ€‹

array: readonly T[]โ€‹

The source array to filter.

values: readonly T[]โ€‹

The values to exclude.

iteratee: (item) => unknown | keyof Tโ€‹

A function or property key to compute the comparison value.


Returns: T[]โ€‹

A new array containing elements whose computed values are not in values.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(n + m) time & space, uses hash map for constant-time lookups.


Also known asโ€‹

differenceBy (Lodash, es-toolkit) ยท differenceWith (Remeda, Ramda, Effect) ยท โŒ (Radashi, Modern Dash, Antfu)


Exampleโ€‹

differenceBy([2.1, 1.2, 3.3], [2.3, 3.4], Math.floor);
// => [1.2]

differenceBy(
[{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }],
[{ id: 2, name: 'Bobby' }],
'id'
);
// => [{ id: 1, name: 'Alice' }]

How it works?โ€‹

Compares elements by a computed key (iteratee) instead of direct equality.


Use Casesโ€‹

Filter out duplicate objects by a specific property ๐Ÿ“Œโ€‹

Remove objects from an array based on a shared property value, not reference equality. Perfect for deduplicating user lists, filtering products, or managing unique entries.

const allUsers = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
{ id: 4, name: "David" },
];
const bannedUsers = [
{ id: 2, name: "Bob" },
{ id: 4, name: "David" },
];

const activeUsers = differenceBy(allUsers, bannedUsers, "id");
// => [{ id: 1, name: "Alice" }, { id: 3, name: "Charlie" }]

Exclude items by computed value using a custom functionโ€‹

Filter out elements based on a transformation or calculation result. Perfect for case-insensitive comparisons, date filtering, or normalized matching.

const allEmails = [
"Alice@company.com",
"BOB@company.com",
"charlie@company.com",
];
const unsubscribed = ["alice@company.com", "bob@company.com"];

const activeEmails = differenceBy(allEmails, unsubscribed, (email) =>
email.toLowerCase()
);
// => ["charlie@company.com"]

Filter items by derived date value using a custom functionโ€‹

Exclude elements based on a computed temporal value like year, month, or quarter. Perfect for archiving old content, filtering reports by period, or managing time-based data.

const articles = [
{ title: "News 1", date: new Date("2024-03-15") },
{ title: "News 2", date: new Date("2025-01-10") },
{ title: "News 3", date: new Date("2024-07-22") },
];
const excludedYears = [{ date: new Date("2024-01-01") }];

const currentYearArticles = differenceBy(articles, excludedYears, (a) =>
a.date.getFullYear()
);
// => [{ title: "News 2", date: 2025-01-10 }]