How to Remove Duplicates from an Array in JavaScript

Getting the unique values of an array with Set, filter and reduce.

You may encounter times when an array ends up with the same value more than once, like tags pulled from a list of posts or ids collected from an API. You can remove the duplicates in one line with a Set.

TL;DR For strings and numbers, [...new Set(array)] returns a new array with the duplicates removed.

Using a Set

A Set is a collection that can only hold each value once. If you pass an array into a new Set, the duplicates are dropped automatically:

const tags = ["js", "react", "js", "css", "react"]
const uniqueTags = new Set(tags)
console.log(uniqueTags) // Set { "js", "react", "css" }

A Set isn't an array though, so you can't call map or filter on it. Turn it back into an array with the spread operator:

const uniqueTags = [...new Set(tags)]
console.log(uniqueTags) // ["js", "react", "css"]

Array.from does the same thing if you prefer to read it as a function call:

const uniqueTags = Array.from(new Set(tags))

Each value stays in the position where it first appeared.

Using filter and indexOf

Before Set this was the common way to do it, and it's still useful to understand. indexOf returns the first index of a value, so an item is only kept if it's the first one of its kind:

const numbers = [1, 2, 2, 3, 1, 4]
const unique = numbers.filter((number, index, array) => {
return array.indexOf(number) === index
})
console.log(unique) // [1, 2, 3, 4]

The second 2 is at index 2, but indexOf(2) returns 1, so it's left out. This gets slow on very large arrays, since indexOf searches the array again for every item.

Removing Duplicate Objects

A Set compares objects by reference, not by what's inside them. Two objects that look the same are still different objects:

const users = [
{ id: 1, name: "Jim" },
{ id: 2, name: "Pam" },
{ id: 1, name: "Jim" },
]
console.log([...new Set(users)].length) // 3

To remove duplicate objects, pick a property that should be unique, like an id, and keep track of the ones you've already seen:

const seen = new Set()
const uniqueUsers = users.filter((user) => {
if (seen.has(user.id)) return false
seen.add(user.id)
return true
})
console.log(uniqueUsers)
// [{ id: 1, name: "Jim" }, { id: 2, name: "Pam" }]

The seen set holds every id we've come across. If an id is already in there, the user is filtered out.

If you'd rather keep the last copy of each object instead of the first, a Map keyed by id does it in one line:

const uniqueUsers = [...new Map(users.map((user) => [user.id, user])).values()]

Later items with the same id replace earlier ones in the Map, and .values() gives you the objects back.

For most arrays of strings and numbers though, [...new Set(array)] is all you need.

Have some feedback on this post? .