What’s a Set?

JakePino
3 min readDec 12, 2020

Being relatively new to coding, I’m finding new things it seems every day. In conversations with a friend, I was introduced to a Set object. So let’s take a look at what this object is, and how we can use it creatively to solve an algorithm.

A Set:

The definition of a Set according to JavaScript docs is as follows: “Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection.”

Basically, a Set acts like a JavaScript object and acts like an array. It needs to be constructed using new Set() and it has specific methods you can call on it, detailed below:

let mySet = new Set()

mySet.add(1) // Set [ 1 ]
mySet.add(5) // Set [ 1, 5 ]
mySet.add(5) // Set [ 1, 5 ]
mySet.add('some text') // Set [ 1, 5, 'some text' ]
let o = {a: 1, b: 2}
mySet.add(o)

mySet.add({a: 1, b: 2}) // o is referencing a different object, so this is okay

mySet.has(1) // true
mySet.has(3) // false, since 3 has not been added to the set
mySet.has(5) // true
mySet.has(Math.sqrt(25)) // true
mySet.has('Some Text'.toLowerCase()) // true
mySet.has(o) // true

mySet.size // 5

mySet.delete(5) // removes 5 from the set
mySet.has(5) // false, 5 has been removed

mySet.size // 4, since we just removed one value

console.log(mySet)
// logs Set(4) [ 1, "some text", {…}, {…} ] in Firefox
// logs Set(4) { 1, "some text", {…}, {…} } in Chrome

The biggest feature of Set’s that make them unique, is that each value must be unique (see what I did there?). Lets examine how this comes in handy with this algorithm.

The above question asks us to check and see if a list of numbers only contains unique numbers. For example, nums = [5, 3, 1, 8, 3, 1, 1, 8, 8, 8] would return true, as there is one 5, two 3’s, three 1’s, and four 8’s, so no number occurs the same amount of times as any other number. So, let's use a Set to solve this!

We make an object to store the occurrences of a number using a for loop. Then, we make a Set and give it the object values. We then compare the Set’s size against the length of those stored values. Since a Set only takes unique numbers, the only way the two can equal each other is if num only has unique occurrences of numbers. Hope this helps!

--

--

JakePino

California native, living in NYC., Software Engineer.