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]