Playing with Sets

Roman Opalacz
3 min readSep 9, 2020

I want to talk about sets in JavaScript because they’ve helped me out a couple times and they seem to be less known than some of JS’s other object types. As you may know, many of JS’s seemingly different data types are just types of objects. For instance, arrays are a type of object. Like arrays, sets let you hold a collection of data, have a size/length property, and are iterable. Unlike objects or arrays, sets can’t return specific values from their collection with bracket notation, but most importantly, they can’t hold duplicate data; this is their main feature! You can use this property to easily filter user input or arrays into just unique data.

To make a set you can use its constructor method:

That last set illustrates the “magic” of sets. They don’t throw errors for having duplicates, but more preferably they prevent duplicate data from being added to their contents.

Sets have several useful and straightforward methods built in, as well:

Sets also a have a few different iteration methods available to them, but several of them are redundant:

entries is actually attempting to log arrays of key:value pairs…

If you’re familiar with ruby, you might fondly recall the array method uniq which would return an array without duplicates. JavaScript has no such method built in to its arrays, but sets offer possibly the simplest way to reach the same solution. The contents of an array can be put into a set, which will in turn remove its duplicates. Then the contents of the set can be put into an array again:

You can go one step further and incorporate sets in your functions if you want to prevent duplicates to begin with. Imagine a function meant to collect user input from an event that you only want unique inputs from:

this function returns a new array but you can just as easily assign to an existing variable or set to state

There’s plenty of other valid ways to accomplish this kind of data filtering too, but if you’ve didn’t know about sets before or if you hadn’t considered using them, then perhaps now you can see the kinds of solutions it offers. The next time time you need unique data, give sets a try! I hope you found this helpful.

--

--

Roman Opalacz

Aspiring software engineer with almost no experience applying logic