Aller au contenu principal

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