unionWith()
unionWith<
T>(arrays,comparator):T[]
Creates an array of unique values from all given arrays using a comparator function.
First occurrence wins when duplicates are found.
Type Parametersโ
T: Tโ
The type of elements in the arrays.
Parametersโ
arrays: readonly (readonly T[])[]โ
The arrays to combine.
comparator: (a, b) => booleanโ
The function invoked to compare elements.
Returns: T[]โ
A new array with unique elements.
Sinceโ
2.0.0
Performanceโ
O(nยฒ) โ custom comparators cannot leverage Set optimization.
Also known asโ
unionWith (Lodash, es-toolkit, Ramda, Effect) ยท โ (Remeda, Radashi, Modern Dash, Antfu)
Exampleโ
const objects = [
[{ x: 1, y: 2 }, { x: 2, y: 1 }],
[{ x: 1, y: 2 }, { x: 3, y: 4 }]
];
unionWith(objects, (a, b) => a.x === b.x && a.y === b.y);
// => [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 3, y: 4 }]
How it works?โ
Deduplicates using a custom comparator function.
Use Casesโ
Merge objects with custom equality ๐โ
Combine arrays using custom comparison logic. Perfect for complex deduplication or merging objects with deep equality.
const localUsers = [
{ email: "alice@example.com", name: "Alice" },
{ email: "bob@example.com", name: "Bob" },
];
const remoteUsers = [
{ email: "ALICE@EXAMPLE.COM", name: "Alice Smith" },
{ email: "charlie@example.com", name: "Charlie" },
];
const allUsers = unionWith(
[localUsers, remoteUsers],
(a, b) => a.email.toLowerCase() === b.email.toLowerCase()
);
// => [Alice, Bob, Charlie] (case-insensitive dedup)
Combine coordinates with toleranceโ
Merge location data where "close enough" is considered equal. Useful for geospatial data or sensor readings.
const sensorA = [
{ lat: 48.856, lng: 2.352 },
{ lat: 51.507, lng: -0.127 },
];
const sensorB = [
{ lat: 48.857, lng: 2.353 }, // ~same as Paris
{ lat: 40.712, lng: -74.006 },
];
const TOLERANCE = 0.01;
const allLocations = unionWith([sensorA, sensorB], (a, b) =>
Math.abs(a.lat - b.lat) < TOLERANCE && Math.abs(a.lng - b.lng) < TOLERANCE
);
// => [Paris, London, NYC]
Merge configs with deep equalityโ
Combine configuration objects avoiding duplicates by deep comparison. Essential for merging settings from multiple sources.
const defaultConfig = [{ key: "theme", value: { mode: "light" } }];
const userConfig = [{ key: "theme", value: { mode: "light" } }];
const deepEqual = (a, b) =>
a.key === b.key && JSON.stringify(a.value) === JSON.stringify(b.value);
const mergedConfig = unionWith([defaultConfig, userConfig], deepEqual);
// => [{ key: "theme", value: { mode: "light" } }] (deduplicated)