How do you remove duplicate values from an array?
For simple values the modern answer is a Set. A set keeps only one copy of each value, and spreading it back into an array gives you the answer in a single line.
const numbers = [1, 2, 2, 3, 3, 3, 4];
console.log([...new Set(numbers)]); // [1, 2, 3, 4]
// The older filter approach gives the same result.
const kept = numbers.filter(function (value, index) {
return numbers.indexOf(value) === index;
});
console.log(kept); // [1, 2, 3, 4]
The Set version is the one to reach for. It runs in linear time because the set does the lookup for you, while the filter version calls indexOf for every value, which becomes slow on a large array. The filter version is still worth recognising, because it is common in older code and because it uses the same style as any other filter you have written.
Two limits are worth knowing. A set compares values with the same rule that === uses, plus one special case where positive zero and negative zero count as the same value. It does not do anything clever with objects, because two separate object literals are never the same value, so a set of objects will keep all of them.
And when your values are objects, you have to decide for yourself what makes two of them duplicates. Usually the answer is a key field such as an id, and then you need a different approach altogether.