I’ve discovered that many of us JavasScript programers haven’t noticed that ECMAScript6 introduced two new types of collections: sets and maps.
Let’s start today with a set. What is it, you may ask? The set is a collection of unique elements.
Try this code:
const log = x => console.log(x);const mySet = new Set();
As you can see, we have only 2 elements in our set, as expected.
We can initialize our set using an array:
const log = x => console.log(x);const mySecondSet = new Set([123,"123",123]);
And convert it to an array (with a little help from a spread operator):
const log = x => console.log(x);const myThirdSet = new Set([123,"123",123]);
const myArray = [...myThirdSet];log(myArray);
With this knowledge we can quickly build functions which removes duplicates from an array :)
const log = x => console.log(x);const removeDuplicates = items => [...new Set(items)];
const arrayWithDuplicates = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6];