Skip to main content

Uniquify array

· 2 min read
Filip Tammergård
Software Engineer at Einride

Consider this array of names:

const names = [
"Filip",
"Anna",
"Jennifer",
"Anna",
"Robert",
"Emma",
"Filip",
"Anna",
]

In this array, Filip occurs two times and Anna three times. What if we want filter out the duplicates and get an array with the unique names?

A perfect use case for the Set object! Set objects can by definition only hold unique values, so when converting an array to a Set object, duplicates are automatically filtered out.

const namesSet = new Set(names)
// > Set(5) {'Filip', 'Anna', 'Jennifer', 'Robert', 'Emma'}

Here we have a Set object with unique names in it! Now we just need to convert the Set object back to an array and then we're done.

Converting a Set object to an array can be done using Array.from():

const uniqueNames = Array.from(namesSet)
// > (5) ['Filip', 'Anna', 'Jennifer', 'Robert', 'Emma']

Another option is using the spread operator:

const uniqueNames = [...namesSet]
// > (5) ['Filip', 'Anna', 'Jennifer', 'Robert', 'Emma']

Full example

Here's the full example doing the two steps in one go:

const names = [
"Filip",
"Anna",
"Jennifer",
"Anna",
"Robert",
"Emma",
"Filip",
"Anna",
]

const uniqueNames = [...new Set(names)]
// > (5) ['Filip', 'Anna', 'Jennifer', 'Robert', 'Emma']

Conclusion

  • Removing duplicates from an array can be done by converting the array to a Set object, and then convert it back to an array.

References