DEV Community

Cover image for What is a Set() ?
Alexa Gamil
Alexa Gamil

Posted on

What is a Set() ?

Set is a data structure that lets you store a collection of UNIQUE values of any type. What I need to emphasize here is that it only allows you to store UNIQUE values. They are similar to Array in the sense that both are a data collection but there are major differences between them.

Set Array
Collection of values of any data Collection of values of any data
Store unique values Values may occur more than once
Ordered by insertion Indexed order
Does not allow random access Retrieve elements using index
Cannot be reordered Can be reordered
Only has limited methods Array has a LOT of methods
You can only add values to the end You can add elements anywhere

How to create a new Set()

new Set()
// Set(0) {}
Enter fullscreen mode Exit fullscreen mode

You can also pass in iterable objects when creating sets.


const harryPotter = new Set([Sorcerers Stone, Chamber of Secrets, Prisoner of Azkaban])
// undefined
harryPotter
// Set(3) {“Sorcerer’s Stone”, “Chamber of Secrets”, “Prisoner of Azkaban”}

const noDuplicates = new Set(banana)
// undefined
noDuplicates
// Set(3) {‘b’, ‘a’, ‘n’}
Enter fullscreen mode Exit fullscreen mode

As you can see from above, when we passed in a string of banana, it only stored the characters b a n

How to find the size of a Set, use the size property

const harryPotter = newSet([Sorcerers Stone, Chamber of Secrets, Prisoner of Azkaban])
harryPotter.size
// 3
Enter fullscreen mode Exit fullscreen mode

How to add a value to a Set, use the add method

const harryPotter = new Set([Sorcerers Stone, Chamber of Secrets, Prisoner of Azkaban])
//undefined
harryPotter.add(Goblet of Fire)
//Set(4) {“Sorcerer’s Stone”, “Chamber of Secrets”, “Prisoner of Azkaban”, “Goblet of Fire”}

Enter fullscreen mode Exit fullscreen mode

Try adding the same title again, the set will not grow.

Hot to delete a value from a Set, use the delete method

harryPotter.delete(Goblet of Fire)
// true
harryPotter 
// Set(3) {"Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"}

Enter fullscreen mode Exit fullscreen mode

You can also clear the whole set with the clear method

harryPotter.clear()
// undefined
harryPotter
// Set(0) {}
Enter fullscreen mode Exit fullscreen mode

How to find out if a value exists in a Set, use the has method

const harryPotter = newSet([Sorcerers Stone, Chamber of Secrets, Prisoner of Azkaban])

harryPotter.has(Sorcerers Stone)
// true
harryPotter.has(Order of the Phoenix)
// false
Enter fullscreen mode Exit fullscreen mode

It’s also important to note that has method only takes a single operation. Lookup time is constant time or O(1).

Sets are iterable

We can use for loops, for...of, and for..each

const harryPotter = new Set(["Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"])
// undefined

harryPotter.forEach(book =>  console.log(`Harry Potter and the ${book}`))
// Harry Potter and the Sorcerer's Stone
// Harry Potter and the Chamber of Secrets
// Harry Potter and the Prisoner of Azkaban
// undefined
Enter fullscreen mode Exit fullscreen mode

How to convert a Set object to an Array object

Using the Array.from() method

const harryPotter = new Set(["Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"])
// undefined

const booksArr = Array.from(harryPotter)
booksArr
// ["Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"]
Enter fullscreen mode Exit fullscreen mode

Or using the spread operator (...)

const booksArr = [...harryPotter]
// undefined
booksArr
// ["Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"]
Enter fullscreen mode Exit fullscreen mode

When to use sets?

Here’s a simple example. You asked your friends for vacation ideas.
In an array, it could look like this.

const locationsArr = [Hawaii, Bali, New York, Japan, Hawaii, Japan, Bali, Thailand ]
Enter fullscreen mode Exit fullscreen mode

But what you really want is this

const locationsSet = new Set(locationsArr)
// undefined
locationsSet
// Set(5) {"Hawaii", "Bali", "New York", "Japan", "Thailand"}
Enter fullscreen mode Exit fullscreen mode

Sets are not meant to replace Arrays. The purpose of Sets is to hold UNIQUE values. Take note that it is also case-sensitive.

new Set("Alexa") // Set(5) {"A", "l", "e", "x", "a"}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (2)

Collapse
 
lexlohr profile image
Alex Lohr

There are a few interesting use cases for sets. For example, if you want to detect if an object has cross-references (which will lead to errors if you traverse it):

const hasCrossReferences = (obj, nodes = new Set()) => {
  if (nodes.has(obj)) {
     return true
  }
  nodes.add(obj)
  return !!obj && typeof obj === 'object' &&
    Object.values(obj)
      .some((node) => hasCrossReferences(node, nodes))
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tolentinoel profile image
Ellaine Tolentino

Thanks for the breakdown! This is timely since I'm trying to learn more about data structures!