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) {}
You can also pass in iterable objects when creating sets.
const harryPotter = new Set([“Sorcerer’s 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’}
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([“Sorcerer’s Stone”, “Chamber of Secrets”, “Prisoner of Azkaban”])
harryPotter.size
// 3
How to add a value to a Set, use the add
method
const harryPotter = new Set([“Sorcerer’s 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”}
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"}
You can also clear the whole set with the clear
method
harryPotter.clear()
// undefined
harryPotter
// Set(0) {}
How to find out if a value exists in a Set, use the has
method
const harryPotter = newSet([“Sorcerer’s Stone”, “Chamber of Secrets”, “Prisoner of Azkaban”])
harryPotter.has(“Sorcerer’s Stone”)
// true
harryPotter.has(“Order of the Phoenix”)
// false
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
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"]
Or using the spread operator (...)
const booksArr = [...harryPotter]
// undefined
booksArr
// ["Sorcerer's Stone", "Chamber of Secrets", "Prisoner of Azkaban"]
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” ]
But what you really want is this
const locationsSet = new Set(locationsArr)
// undefined
locationsSet
// Set(5) {"Hawaii", "Bali", "New York", "Japan", "Thailand"}
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"}
Thanks for reading!
Top comments (2)
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):
Thanks for the breakdown! This is timely since I'm trying to learn more about data structures!