Aller au contenu principal

uniqWith()

uniqWith<T>(array, comparator): T[]

Creates a duplicate-free version of an array using a comparator function.

remarque

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]