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"]
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.
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"]
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.