For more tips like this, sign up to the weekly newsletter!

Use a Set to remove duplicates

If you have a list of primitive values (like strings or numbers) and want to filter out the duplicates, you have several options. Since ES6, the easiest is to construct a Set, as that is designed to hold only unique values.

Let's say you have an Array of numbers:

const input = [1, 5, 4, 5, 3, 8, 3, 1, 2];

To construct a Set using these values, use new Set(input).

A Set is an iterable structure, so that you can use it in a for..of loop directly, and every other place that supports iterables.

But if you need an Array, convert it back to one:

[...new Set(input)] // [1, 5, 4, 3, 8, 2]

The Set preserves insertion order. The result will contain the elements in the same order they were in the input.

Not only this is the shortest, but also it is the most performant solution to this problem.

Try it
References
Learn more: