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];
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
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] 🤩
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] 🤩
See this example live in JSBin.