Set data structures
set data structures
what I will be covering in this article
- What is the set data structure.
- How to use the set data structure.
- When to use the set data structure.
What is the set data structure
A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
Methods
new Set(iterable)
– creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
set.add(value)
– adds a value, returns the set itself.
set.delete(value)
– removes the value, returns true if value existed at the moment of the call, otherwise false.
set.has(value)
– returns true if the value exists in the set, otherwise false.
set.clear()
– removes everything from the set.
set.forEach()
– iterate of the map similar to how it would work with an array.
set.size
– is the elements count.
The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason why each value appears in a Set only once.
For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.
How to use the set data structure.
The strength of this data structure is that it is more efficient then others for data that is changing often. You don’t have to iterate through to delete a value and you know with certainly that when you delete a value that value no longer exists within.
We can use Object.fromEntries to get a plain object from Map. A call to map_var.entries() returns an iterable of key/value pairs, exactly in the right format for Object.fromEntries.