An Introduction to Sets in JavaScript

Using sets to deal with unique elements in a dataset

Photo by JOSHUA COLEMAN on Unsplash

Sets are a new object type included in ES6 that allow the creation of collections of unique values. The values in a set can be either simple primitives like strings and integers or more complex object types like object literals or arrays. Think of sets as an array with no repeated elements.

There are many instances where we have an array containing many elements that we want to convert to a unique array. While it can be done by brute force on the array, checking elements, using loops, distinct callback method, etc., the best method is using set().

Syntax:

new Set([iterable]);

Let’s first see an example:

It is clear from the example that by making a new set from an array and using the spread operator, you can make a set into an array.