Using JavaScript Sets

Some Interesting Uses, Observations and Gotchas

gravity well
Nov 29 · 5 min read
Photo by Guillaume Bolduc on Unsplash

JavaScript Sets are a great way to keep a collection of unique values. Since they store values, one might think they are similar to arrays, but they are quite different.

In this article I’d like us to understand the basics of Sets go over a few uses and a few “gotchas.”

A full explanation of JavaScript Sets, properties and methods can be found here.

The Basics

The Set object lets you store unique values of any type, whether primitive values or object references.

The keyword here is unique. As we will see in a moment, even if we fill a Set with non-unique values, it only returns unique values. Well, in most cases. Just wait!

The syntax is,

new Set([iterable]);

If an iterable object is passed, all of its elements will be added to the new Set. If you don't specify this parameter, or its value is null, the new Set is empty.

The concept of iterable is also quite important here. Typical iterable objects are strings, arrays and maps (there are others.)

If you’ve read some of my other articles, you are aware I often start of with problems or issues. This is to give us a deeper understanding by “solving the problem.”

Notice this possibly non-intuitive behavior. Here we will create an Array of integers, quite simple. But then try to create a Set of the same integers.

Arrays of integers

Now let’s try to create a Set of the same integers. Notice the debugger message.

Epic fail

We can try one more time using the .entries() method of the Set.

The .entries() method of a Set returns an iterable Object.

This will fail as well. But you at least you now know there is a .entries() method.

Same error

The problem is clearly how we defined the Set. As stated in the definition, when creating a new Set Object, it has to be passed an iterable object.

Or

We can create an empty Set and use it’s .add() method.

We will use the latter method first and the first method in an interesting use of Sets.

We will also see that a Set has a .size property.

Notice unique list of 4 items

Beautiful! Not only does this work, but as a Set is supposed to have, it contains only unique values.

Since a Set, when created, is either empty and has items added as above or can be passed an iterable object, such as an Array (hint, hint), we can use this to get an Array of unique values.

So we will learn of another way to get our set of integers but also a neat use of Sets.

Building an Array of unique objects using a Set.

In the process of doing this we will notice some other possible, not so intuitive things.

Notice what the Set contains
  • The Set does not contain one item, the Array. (That’s a different problem we will solve.)
  • The Array was deconstructed and elements put in to the set.
  • We do get a beautiful Set of unique values.

This begs a question though. If the Array is deconstructed, could we ever have a Set of Arrays? The answer is Yes! We’ll explore this later. Pay close attention to how it is done when we get there.


Back to getting our Array of unique values

We have our unique values, but they are locked away in a Set. How do we get them back in to an Array?

We cannot just say something like this,

let unique=[s1];

That would create an array of one item. That one item being a Set. We need to “Spread” the Set’s values out. We will use the Spread … operator.

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

A Set and the Spread operator at work

We mentioned earlier that because Arrays are deconstructed when passed as a parameter to a new Set, it makes creating a Set of Arrays a bit difficult. But, it can be done!

Notice some problems first (me an my problems.)

It ignored a2

The problem is clear, we did not pass an iterable in the constructor. Well, we sort of did. So we get a weird result, a Set containing the first Array’s items. This is a real “gotcha.” It did not throw an exception, it just gave a weird result.

Empty Set and .add() to the rescue again!

A nice Set of 3 Arrays

One last example. What would we get if two arrays has the same values? Inquiring minds want to know!

Hmmm

Maybe this is what you expected, maybe not.

At first thought one might think since a Set contains unique items the Array, a3, might not be displayed and size of the Set s2 would be 2.

But nooo. Why? For a more full explanation read this but the gist is that Arrays are not primitive, so what we get is a reference to their location in memory, which is different for each Array, hence, they are unique.

Conclusion

Sets are cool. But they can be tricky. They make us think very carefully about what is going in to the Set and how we get items in to the Set.

We also saw a simple way to create an Array of unique values from an Array of non-unique values.

There are other properties and methods, so explore. Maybe even try creating a Set of Sets.

By the way. Does a Set of All Sets contain itself?

Thank you for reading and happy coding!

JavaScript in Plain English

Learn the web's most important programming language.

gravity well

Written by

Long time Software Developer, Trainer, Consultant. Keeping up to date. I’ve noticed in over 28 years of programming, one’s current skills have a shelf life.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade