How do you remove duplicates from an array?
The cleanest way to remove duplicates is a Set, which only stores unique values.
Set approach — wrap the array in a Set and spread it back to an array. Short and fast (O(n)).
filter + indexOf — keep an item only if its first index matches the current one. Works but slower (O(n²)).
Arrays of objects — dedupe by a chosen key using a Map or a "seen" set.
Preferred: the Set method for primitives — concise and efficient.
const numbers = [1, 2, 3, 2, 1, 4, 5, 4];
// Method 1: Set (recommended for primitives)
const unique1 = [...new Set(numbers)]; // [1, 2, 3, 4, 5]
// Method 2: filter + indexOf
const unique2 = numbers.filter((item, index) =>
numbers.indexOf(item) === index
); // [1, 2, 3, 4, 5]
// Method 3: reduce
const unique3 = numbers.reduce((acc, item) => {
if (!acc.includes(item)) acc.push(item);
return acc;
}, []);
// For objects: deduplicate by property
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' } // Duplicate
];
const uniqueUsers = [...new Map(users.map(u => [u.id, u])).values()];
// [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
// Or with reduce
const uniqueById = users.reduce((acc, user) => {
if (!acc.find(u => u.id === user.id)) acc.push(user);
return acc;
}, []);Set automatically removes duplicate primitives. filter+indexOf keeps only first occurrences. For objects, Map with id as key deduplicates efficiently — Map.values() returns unique objects.
The reduce approach checks for existing items before adding.
[...new Set(arr)] for primitives is the one-liner answer. Know that Set does not work for object deduplication (reference comparison).
The Map approach for object deduplication by property is the advanced answer. Performance: Set is O(n), filter+indexOf is O(n²).