Skip to main content

uniqBy()

uniqBy<T, Key>(array, iteratee): T[]

Creates a duplicate-free version of an array using an iteratee for comparison.

๐Ÿ’Ž Why is this a Hidden Gem?

Removes duplicates based on a computed key or property. Unlike simple uniq, this handles objects by letting you specify what makes them "equal". Essential for deduplicating API responses, removing duplicate records by ID, or filtering unique items by any property.

note

First occurrence wins when duplicates are found.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.

Key: Keyโ€‹

The type of the comparison key.


Parametersโ€‹

array: readonly T[]โ€‹

The array to inspect.

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) โ€” uses Set for constant-time lookups.


Also known asโ€‹

dedupeWith (Effect) ยท uniqBy (Lodash, es-toolkit, Remeda, Ramda) ยท unique (Radashi) ยท uniqueBy (Antfu) ยท โŒ (Modern Dash)


Exampleโ€‹

uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]

uniqBy(
[{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 1, name: 'c' }],
item => item.id
);
// => [{ id: 1, name: 'a' }, { id: 2, name: 'b' }]

How it works?โ€‹

Removes duplicates by comparing computed keys. First occurrence wins.


Use Casesโ€‹

Remove duplicate objects by ID ๐Ÿ“Œโ€‹

Deduplicate an array of objects based on a unique identifier. Essential for cleaning API responses or normalizing data.

const users = [
{ id: 1, name: "Alice", email: "alice@example.com" },
{ id: 2, name: "Bob", email: "bob@example.com" },
{ id: 1, name: "Alice Smith", email: "alice.smith@example.com" },
{ id: 3, name: "Charlie", email: "charlie@example.com" },
];

const uniqueUsers = uniqBy(users, (u) => u.id);
// => [
// { id: 1, name: "Alice", email: "alice@example.com" },
// { id: 2, name: "Bob", email: "bob@example.com" },
// { id: 3, name: "Charlie", email: "charlie@example.com" }
// ]

Filter unique products by SKUโ€‹

Ensure each product appears only once in a catalog. Perfect for inventory management or e-commerce listings.

const products = [
{ sku: "LAPTOP-001", name: "Pro Laptop", price: 1299 },
{ sku: "MOUSE-001", name: "Wireless Mouse", price: 49 },
{ sku: "LAPTOP-001", name: "Pro Laptop v2", price: 1399 },
];

const uniqueProducts = uniqBy(products, "sku");
// => [LAPTOP-001, MOUSE-001] (first occurrence kept)

Get unique entries by computed valueโ€‹

Deduplicate based on a derived or transformed value. Useful for case-insensitive deduplication or domain extraction.

const emails = [
"alice@gmail.com",
"ALICE@GMAIL.COM",
"bob@yahoo.com",
"Alice@Gmail.Com",
];

const uniqueEmails = uniqBy(emails, (e) => e.toLowerCase());
// => ["alice@gmail.com", "bob@yahoo.com"]