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.
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"]