uniqWith()
uniqWith<
T>(array,comparator):T[]
Creates a duplicate-free version of an array using a comparator function.
note
First occurrence wins when duplicates are found.
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
array: readonly T[]โ
The array to inspect.
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.
Exampleโ
const objects = [{ x: 1, y: 2 }, { x: 2, y: 1 }, { x: 1, y: 2 }];
uniqWith(objects, (a, b) => a.x === b.x && a.y === b.y);
// => [{ x: 1, y: 2 }, { x: 2, y: 1 }]
How it works?โ
Removes duplicates using a custom comparator function. First occurrence wins.
Use Casesโ
Deduplicate with custom equality ๐โ
Remove duplicates using a custom comparison function. Perfect for complex objects or fuzzy matching.
const products = [
{ name: "Laptop", price: 999.99 },
{ name: "LAPTOP", price: 999.99 },
{ name: "Phone", price: 699 },
];
const unique = uniqWith(
products,
(a, b) => a.name.toLowerCase() === b.name.toLowerCase() && a.price === b.price
);
// => [Laptop, Phone]
Remove near-duplicates with toleranceโ
Deduplicate numeric values within a tolerance range. Useful for sensor data, measurements, or approximate matching.
const readings = [10.01, 10.02, 20.0, 10.03, 30.0];
const unique = uniqWith(readings, (a, b) => Math.abs(a - b) < 0.1);
// => [10.01, 20.0, 30.0]
Deep equality deduplicationโ
Remove duplicates based on deep object comparison. Essential for complex nested structures.
const configs = [
{ settings: { theme: "dark", lang: "en" } },
{ settings: { theme: "dark", lang: "en" } },
{ settings: { theme: "light", lang: "fr" } },
];
const unique = uniqWith(
configs,
(a, b) => JSON.stringify(a.settings) === JSON.stringify(b.settings)
);
// => [dark/en, light/fr]