Aller au contenu principal

uniq()

uniq<T>(array): T[]

Creates a duplicate-free version of an array.

remarque

Uses strict equality (===). First occurrence wins.


Type Parameters

T: T

The type of elements in the array.


Parameters

array: readonly T[]

The array to inspect.


Returns: T[]

A new array with unique values, preserving order of first occurrence.


Since

2.0.0


Performance

O(n·k) linear scan for small arrays (≤200), O(n) with Set for larger ones.


Also known as

dedupe (Effect) · uniq (Lodash, es-toolkit, Remeda, Ramda, Antfu) · unique (Radashi, Modern Dash)


Example

uniq([1, 2, 2, 3, 4, 4, 5]);
// => [1, 2, 3, 4, 5]

uniq([11, 2, 3, 44, 11, 2, 3]);
// => [11, 2, 3, 44]

How it works?

Removes duplicates using strict equality (===). First occurrence wins.


Use Cases

Remove duplicate values from a collection 📌

Remove repeated values from an array, keeping only the first occurrence. Essential for cleaning up lists of IDs, tags, or any primitive values.

const selectedIds = [3, 7, 3, 12, 7, 5, 12];

const uniqueIds = uniq(selectedIds);
// => [3, 7, 12, 5]

Clean up user tags 📌

Ensure a tag list contains no repeated entries after user input. Perfect for form handling, content tagging, or search filters.

const userTags = ["react", "typescript", "react", "nodejs", "typescript"];

const cleanTags = uniq(userTags);
// => ["react", "typescript", "nodejs"]

Collect unique categories from a dataset

Extract all distinct values after mapping a property from objects. Useful for building filter menus or faceted navigation.

const products = [
{ name: "Laptop", category: "electronics" },
{ name: "Shirt", category: "clothing" },
{ name: "Phone", category: "electronics" },
{ name: "Pants", category: "clothing" },
{ name: "Tablet", category: "electronics" },
];

const categories = uniq(products.map((p) => p.category));
// => ["electronics", "clothing"]

Deduplicate merged search results from multiple sources

Remove duplicates when combining results from multiple search providers. Common when aggregating results from Algolia, Elasticsearch, and local DB.

const algoliaResults = ["doc-1", "doc-3", "doc-5", "doc-7"];
const dbResults = ["doc-2", "doc-3", "doc-4", "doc-5"];

const allResults = uniq([...algoliaResults, ...dbResults]);
// => ["doc-1", "doc-3", "doc-5", "doc-7", "doc-2", "doc-4"]

Ensure idempotent event processing

Collect unique event IDs to avoid processing the same event twice. Critical for webhook handlers, message queues, and event-driven architectures.

const processedEventIds: string[] = [];

function handleEvent(eventId: string, payload: unknown) {
const seen = uniq([...processedEventIds, eventId]);
if (seen.length === processedEventIds.length) {
return; // Already processed, skip
}
processedEventIds.push(eventId);
processPayload(payload);
}