unionBy()
unionBy<
T,Key>(arrays,iteratee):T[]
Creates an array of unique values from multiple arrays, using an iteratee for comparison.
First occurrence wins when duplicates are found.
Type Parametersβ
T: Tβ
The type of elements in the arrays.
Key: Keyβ
The type of the comparison key.
Parametersβ
arrays: readonly (readonly T[])[]β
An array of arrays to combine.
iteratee: (item) => Keyβ
A function that produces the key for each element.
Returns: T[]β
A new array with unique elements based on the iteratee key.
Sinceβ
2.0.0
Performanceβ
O(n) where n = total elements across all arrays β Set provides O(1) lookups.
Also known asβ
union (Remeda) Β· unionBy (Lodash, es-toolkit) Β· unionWith (Ramda, Effect) Β· unique (Radashi) Β· β (Modern Dash, Antfu)
Exampleβ
unionBy(
[[{ id: 1 }, { id: 2 }], [{ id: 1 }, { id: 3 }]],
(item) => item.id
);
// => [{ id: 1 }, { id: 2 }, { id: 3 }]
unionBy([[1.1, 2.5], [2.2, 3.1]], Math.floor);
// => [1.1, 2.5, 3.1]
How it works?β
Deduplicates by a computed key instead of direct equality.
Use Casesβ
Merge user lists from multiple sources πβ
Combine users from different systems while keeping unique entries by ID. Perfect for CRM integrations, data migrations, or user syncing.
const crmUsers = [
{ id: 1, name: "Alice", source: "crm" },
{ id: 2, name: "Bob", source: "crm" },
];
const marketingUsers = [
{ id: 2, name: "Bob M.", source: "marketing" },
{ id: 3, name: "Charlie", source: "marketing" },
];
const allUsers = unionBy([crmUsers, marketingUsers], (u) => u.id);
// => [Alice, Bob (from CRM), Charlie]
Consolidate product catalogs by SKUβ
Merge inventory from different suppliers without duplicates. Ideal for marketplaces, inventory management, or price aggregators.
const vendorA = [
{ sku: "LAPTOP-001", name: "Pro Laptop", price: 1299 },
{ sku: "MOUSE-001", name: "Wireless Mouse", price: 49 },
];
const vendorB = [
{ sku: "MOUSE-001", name: "Mouse Pro", price: 45 },
{ sku: "MONITOR-001", name: "4K Monitor", price: 399 },
];
const catalog = unionBy([vendorA, vendorB], (p) => p.sku);
// => [LAPTOP-001, MOUSE-001 (from A), MONITOR-001]
Aggregate events from multiple calendarsβ
Combine schedules avoiding duplicate meetings by unique ID. Useful for calendar apps or availability checkers.
const workCalendar = [
{ uid: "evt-001", title: "Team Standup" },
{ uid: "evt-002", title: "Project Review" },
];
const personalCalendar = [
{ uid: "evt-001", title: "Standup (synced)" },
{ uid: "evt-003", title: "Gym Session" },
];
const allEvents = unionBy([workCalendar, personalCalendar], (e) => e.uid);
// => [evt-001 (work version), evt-002, evt-003]