DEV Community

Cover image for How to remove duplicate or repeated elements from an array in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to remove duplicate or repeated elements from an array in JavaScript?

Originally posted here!

To remove duplicate or repeated elements from an array, you can use the Set() constructor function to create unique values from an array and then use the ... spread operator to spread the values to a new array.

Consider this array of numbers with some numbers repeated,

// numbers array with
// some repeated numbers
const numsArray = [23, 45, 32, 23, 23];
Enter fullscreen mode Exit fullscreen mode

Let's remove all the repeated or duplicate elements from the array by passing the numsArray as an argument to the Set() cosntructor function like this,

// numbers array with some
// some repeated
const numsArray = [23, 45, 32, 23, 23];

// Use Set() constructor function
// to remove repeated or duplicate elements
// from an array
const uniqueValues = new Set(numsArray);

console.dir(uniqueValues); // [object Set] 😕 - Not what we expected
Enter fullscreen mode Exit fullscreen mode

Now the uniqueValues variable holds a Set object which is not useful to us here. We need it to be an array.

Since Set objects are iterable, We can use the spread operator (...) on the uniqueValues variable to spread the values to another array like this,

// numbers array with some
// some repeated
const numsArray = [23, 45, 32, 23, 23];

// Use Set() constructor function
// to remove repeated or duplicate elements
// from an array
const uniqueValues = new Set(numsArray);

// using the spread operator (...)
// to get the values to an array
const uniqueValuesArr = [...uniqueValues];

console.log(uniqueValuesArr); // [23, 45, 32] 🤩
Enter fullscreen mode Exit fullscreen mode

Cool! Right? 🔥

The above code can be further reduced like this,

// numbers array with some
// some repeated
const numsArray = [23, 45, 32, 23, 23];

// using the spread operator (...)
// to get the values to an array
const uniqueValuesArr = [...new Set(numsArray)];

console.log(uniqueValuesArr); // [23, 45, 32] 🤩
Enter fullscreen mode Exit fullscreen mode

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Top comments (0)