Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function uniqueBy(array, getKey = (item) => item) {
const seen = new Set();
return array.filter((item) => {
const key = getKey(item);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}Example / expected output
uniqueBy([{ id: 1 }, { id: 2 }, { id: 1 }], (u) => u.id) // [{ id: 1 }, { id: 2 }]How it works
For primitives [...new Set(array)] is enough. For objects, pass a function that returns the identity of each item. The first occurrence wins and the original order is preserved.
Related snippets
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.
- TypeScript Tested
Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.

