Set collection has been introduced which is really good and makes our life simple.
Set is a collection which will not keep duplicates. It can also take any iterable objects as constructor arguments. In our case, it is an array with duplicated values.
const duplicates = [1, 2, 3, 3, 2, 1]const unique = [...new Set(duplicates)]console.log(unique) // [ 1, 2, 3 ]
It is better to know more options, in case of not-so-friendly environment. For instance,
Set collection is supported by all the major browsers but few old-schools. Yes, I am looking at you IE! O_o
const duplicates = [1, 2, 3, 3, 2, 1];const unique = duplicates.filter((item, index) => duplicates.indexOf(item) === index);console.log(unique); // [ 1, 2, 3 ]
Please prefer the
Set option just for the simple of it!
We can do the same
.foreachas well. But,
.filteris more readable among those! ^_^