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]