How to remove duplicate values in a Javascript array
September 21, 2020
A common task I need to do when I’m programming is to remove duplicate values from an array. The code to do this looks like:
const arrayWithDuplicates = [6, 7, 7, 7, 9, 9, 10]
const arrayWithOnlyUniqueValues = [...new Set(arrayWithDuplicates)]
// arrayWithOnlyUniqueValues contains -> [6, 7, 9, 10]
How does it work?
The code above uses the spread syntax and a Set in order to accomplish removing the duplicate values.
When we pass in an array to a Set it will remove all of the duplicate values (as a Set object will only store unique values).
new Set([6, 7, 7, 7, 9, 9, 10])
// The code above will return a set containing -> {6, 7, 9, 10}
We can then use the Spread syntax to expand the values from the set into a new array.