Remove Duplicate Values from a JavaScript Array

In this tutorial, you will see how to remove duplicate values from a JavaScript array with simple and quick examples of JS code.

First of all, I would like to let you know that, there are multiple ways are there to do this task. Here you are going to see two different ways to remove duplicates from an array.

Remove duplicate array values using the Set object

Removing duplicates from an array using the Set method is the easiest way. At least, in my opinion, there are no other ways simpler than using the Set(). Using this method, the task can be done just in two lines of code quickly.

Below is how we do it with the Set() object:

var clrs = ['red', 'green', 'red', 'blue', 'black', 'black', 'yellow', 'indigo'];
var uniqueClrs = [...new Set(clrs)];
console.log(uniqueClrs); // ["red", "green", "blue", "black", "yellow", "indigo"]

That’s it…

You have seen how we did it just within two lines of code and the extra line is for showing the result in the console log. We have just created a new SET() object and pass our array as the parameter.

Also, read:

 

Using JavaScript filter()

We can also remove duplicate array values using the JavaScript filter() method. Below is the JS code where we have used the filter method:

var clrs = ['red', 'green', 'red', 'blue', 'black', 'black', 'yellow', 'indigo'];
var inx = (clrs) => clrs.filter((v,i) => clrs.indexOf(v) === i)
uniqueClrs = inx(clrs);
console.log(uniqueClrs); // ["red", "green", "blue", "black", "yellow", "indigo"]

 

So we have seen two different ways that can remove duplicate values from our JavaScript array.

There are some more ways to do this task may exist. You can do it even by using the forEach(). But, here I am not going to show the example using the forEach(), because it will need some more lines of code and a little bit complicated. I want to keep our tutorial simple.

 

Leave a Reply

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