Forward Thinking — a never-complete guide to modern JavaScript #3 — Sets

Tomasz Zwierzchoń
Nov 6, 2017 · 1 min read

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();
mySet.add(123);
mySet.add('123');
mySet.add(123);
log(mySet);

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]);
mySecondSet.add("123");
log(mySecondSet);

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];
log(removeDuplicates(arrayWithDuplicates));

More about Sets here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Orba

We create and develop B2B & B2C e-commerce systems

Tomasz Zwierzchoń

Written by

IT Architect. FrontEnd Team Lead. #JavaScript on #IoT #UX #Vue.js Fan. I miss having free time, especially for dancing Tango.

Orba

We create and develop B2B & B2C e-commerce systems