Sometimes, we want to delete duplicate elements from an array with JavaScript.
In this article, we’ll look at how to delete duplicate elements from an array with JavaScript.
Delete Duplicate Elements From an Array with JavaScript
To delete duplicate elements from an array with JavaScript, we can use the array filter
method or the Set
constructor with the spread operator.
For instance, we can use the array filter
method by writing:
const arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]
const unique = arr.filter((elem, index, self) => {
return index === self.indexOf(elem);
})
console.log(unique)
We call filter
with a callback that checks if index
is the same as the index returned by indexOf
called on the self
array with elem
.
If it’s not the first instance of elem
, then they’ll be different.
self
is the same as arr
.
Therefore, duplicate instances of elem
won’t be present in arr
.
So unique
is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Likewise, we can use the Set
constructor with the spread operator to remove the duplicates.
For instance, we can write:
const arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10]
const unique = [...new Set(arr)]
console.log(unique)
We pass arr
into the Set
constructor to convert arr
to a set to remove the duplicate elements.
Then we spread that back into an array to convert the set back into an array.
And therefore, unique
is the same result as before.
Conclusion
To delete duplicate elements from an array with JavaScript, we can use the array filter
method or the Set
constructor with the spread operator.