More JavaScript answers

by Danny
Published 2 min read

Use a Set to remove duplicate primitive values in one line. For arrays of objects, deduplicate by a key with a Map. Here is when to use each approach.

The short answer

#

For strings, numbers and other primitive values, pass the array to a Set and spread it back into an array. A Set only keeps one copy of each value and keeps the order of first appearance. For objects, deduplicate by a key such as id instead.


_10
const tags = ['js', 'css', 'js', 'html', 'css'];
_10
const unique = [...new Set(tags)];
_10
// ['js', 'css', 'html']

Why it happens

#

JavaScript arrays allow repeated values, so duplicates usually come from merging lists, concatenating API pages, or pushing items in a loop. Removing them depends on what "the same" means:

  • Primitive values are equal when they have the same value, so Set works directly.
  • Objects are compared by reference. Two objects with the same fields are still different values, so new Set(users) keeps both. You need to choose a key that identifies a duplicate.

Set uses the SameValueZero comparison. That means NaN matches NaN, and 0 matches -0, which is usually what you want.

How to fix it

#

Primitives: use a Set

This is the shortest and fastest option for primitives, and it runs in linear time.


_10
const ids = [3, 1, 3, 2, 1];
_10
const uniqueIds = Array.from(new Set(ids));
_10
// [3, 1, 2]

Array.from and the spread syntax do the same thing here; pick whichever reads better to you.

Objects: deduplicate by a key with a Map

Build a Map keyed by the identifying property, then take its values. With this version, the last item with a given key wins.


_10
const users = [
_10
{ id: 1, name: 'Ada' },
_10
{ id: 2, name: 'Grace' },
_10
{ id: 1, name: 'Ada L.' },
_10
];
_10
_10
const byId = [...new Map(users.map((user) => [user.id, user])).values()];
_10
// [{ id: 1, name: 'Ada L.' }, { id: 2, name: 'Grace' }]

To keep the first item instead, track the keys you have seen:


_11
function uniqueBy(items, getKey) {
_11
const seen = new Set();
_11
return items.filter((item) => {
_11
const key = getKey(item);
_11
if (seen.has(key)) return false;
_11
seen.add(key);
_11
return true;
_11
});
_11
}
_11
_11
const firstById = uniqueBy(users, (user) => user.id);

The key function can combine fields too, for example (item) => item.date + '|' + item.room.

Using filter and indexOf

You will often see this older pattern. It works for primitives, but it scans the array for every item, so it gets slow on large arrays.


_10
const unique = tags.filter((tag, index) => tags.indexOf(tag) === index);

It also fails to remove repeated NaN values, because indexOf never finds NaN. Prefer Set unless you need to support very old environments.

Case-insensitive or trimmed values

Normalise the value and use it as the key so that 'React' and 'react ' count as the same.


_10
const cleaned = uniqueBy(names, (name) => name.trim().toLowerCase());

Common pitfalls

#
  • Expecting new Set(objects) to remove objects that look the same. It only removes the exact same reference.
  • Using JSON.stringify as a key for whole objects. It is slow and treats the same fields in a different order as different.
  • Forgetting that the Map version keeps the last match while uniqueBy keeps the first. Choose on purpose.
  • Mutating the original array. All the approaches above return a new array and leave the input unchanged.
#

Was this resource helpful?