Max Zander

Posted on

ðŸŽ¶ Let's talk about sets... ðŸŽ¶

So if you read my blog post Data: Types vs. Structures, you might recall me talking about a data structure known as a Set. I was doing a code challenge this last week and found sets to be incredibly helpful in finding an efficient solution, so I decided to take a minute this week to ðŸŽµtalk about sets (baby)ðŸŽµ.

Sets (or set objects) are a collection of values and, as I mentioned in my aforementioned previous post, the values in a set are unique (meaning they can only occur once). This can prove super helpful for finding out if something belongs to a set of values or if you need to figure out how many unique values exist in a a given set of data.

So now that we've established what sets are, let's talk a little bit about how to use them:

First of all, how do we create a set? Well, to create a new set we say:

``````new Set()
``````

and if we want to add an argument, we can either add data directly:

``````let triadSet = new Set([1, 3, 5])
// the Set now looks like this: [1, 3, 5]
``````

or we can convert existing data to a set:

``````let array = [1, 3, 5, 3, 1]
// the Set now looks like this: [1, 3, 5]
``````

You'll note that the `triadSetFromArray` doesn't repeat the second `3` or `1` because (again), the values in a set are unique!

If we want to add to our set, we can call a method `add()` to do so:

``````triadSetFromArray.add(8);
// the Set now looks like this: [1, 3, 5, 8]
``````

N.B. The `add()` method adds the new element to the end of the set object.

If you want to remove an element from a set object, you can do that by calling the `delete()` method:

``````triadSetFromArray.delete(8);
// the Set now looks like this: [1, 3, 5]
``````

So let's say you've created your great new set, `triadSetFromArray` and you want to check what it contains. Sets have a method `has()` that you can call to check on the contents. `has()` returns a boolean value depending on the contents and works like this:

``````triadSetFromArray.has(5);
// true

// false
``````

Now let's say you've been given the array above and are tasked with returning the amount of unique items exist in the array. Well, sets have a `size` property that you can call to retrieve that kind of data.

``````let array = [1, 3, 5, 3, 1]

And if you decide that you're over the entire set object and you want to get clear out the whole thing (or, you know, you have a better reason to do it ðŸ˜‰), you can call the `clear()` method to do so:
``````triadSetFromArray.clear();