Remove duplicate values from an array

Darren Jones
May 6, 2021

To remove duplicate values from an array, you can create a new Set object with the array as a parameter to the constructor function. You can then convert the Set back into an array using the spread operator:

copy code
const duplicates= [1,2,2,3,3,3,4,4,4,4];
// [1,2,2,3,3,3,4,4,4,4]
const noDuplicates = [ Set(duplicates)];
// [1,2,3,4]

This works because a set object can only contain one of each value, so any duplicate values provided in the constructor’s argument will be removed. The spread operator can then be used to convert the set into a new array.

Know a better answer? Join our our community and let us know.