While researching Javascript data structures, I came across a data structure called a Set. I decided to delve a bit deeper into what constitutes a set, how it differs from an array, and ways that it could be useful in solving problems.

What is a set?

A set is an object that is a collection of values. It is iterable based on the insertion order, and each value can only occur once in a set.

How do you create a new set?

You can create a new set by writing the following:

let mySet = new Set()

By writing ‘new Set()’, you are creating a new instance of a Set object.

What methods can you perform on a set?

To add an item to a set, you can use the method ‘.add’, which will add the item to the end of the set and return the Set object. You can only add one item at a time when you use ‘.add’.

mySet.add(3)  //returns Set { 3 } 

You can also add an object to a set:

mySet.add({'a': 1, 'b': 2}) // returns Set { 3, {a: 1, b: 2}}

There are several ways to add an array to a set. You can add the array when you create a new instance of the set:

const s = new Set([1, 2, 3]) //s = Set { 1, 2, 3}

If you have already created a new set, you can iterate through the array and add each element of the array to the set.

const t = new Set()

To check if an item exists in a set, you can use the ‘.has’ method, which returns a boolean value.

t.has(1) // true 
t.has('a') //false

The .delete method will remove an element from the set:

t.delete(1) 

Collecting Unique Values

Because the set will only store unique values, this can be helpful when reducing an array to its unique items. If you wanted to remove duplicates in an array, you can convert it to a set, then back to an array.

const a = [1, 1, 2, 3, 3]

Size Property

The .size property of a set will return the number of values contained within the set. It is similar to calling .length on an array.

t.size // = 1

Important Differences between Sets and Arrays

  1. Unlike an array, a set is unordered, so you cannot access an item through its index. Instead, you would have to use the .has method to check if an item exists in the set.
  2. The runtimes of operations can vary based on whether you use a set or array. Here is an interesting article comparing and contrasting the different runtimes: https://stackoverflow.com/questions/39007637/javascript-set-vs-array-performance.

Sources:

https://stackoverflow.com/questions/8338133/set-vs-array-difference