Categories
JavaScript Answers

How to Delete Duplicate Elements From an Array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *