Set was introduced in ES6 and is a collection of values without keys. It has one killer feature that you want to use - filtering duplicates owing to its feature of allowing only unique values.
So.. set?
People from other languages may be familiar with sets, maps and arrays.. and the confusion that comes with them.
- What is a set (map, or array)?
- Why should I use it?
- When should I use what?
- How is it different?
- Why am I alive?
- What is the purpose of life?
As a Javascript developer, I was immune to that - use arrays for series of elements, objects for rest (aka keyed elements).
Except - if you want to avoid duplicates easily, or not iterate whenever you want specific elements - then you definitely want to use objects. And oh.. I completely ignore maps - because I can. And also because I (probably unconsciously) avoid situations that requires weird keys.
Sorry.. getting back to the drawing board - set.
As I was saying Sets are introduced in ES6. They can be treated as ‘special’ type of collections that support typical collection operations.
Create set and add elements
Just like its collection management cousins, set is initiated and used quite easily.
|
|
However, adding same elements will not yield any changes in the set.
|
|
The behaviour in a set of objects is slightly more complicated. The below code where you add the exact object will avoid the duplicates.
|
|
However the below code will take in everything.
|
|
Duplicate objects like these are allowed because set determined object uniqueness by reference and not value.
Iterating a set
Use a for
/of
, or forEach
.
|
|
Deleting stuff
Remove an element from set.
|
|
Clear everything out.
|
|
Other Cool Features
How many elements are plonked in the set so far?
|
|
Check whether a value already exists.
|
|
Why should you use set?
-
Two words - avoid duplicates.
Set does not need loops to catch duplicates. -
Has a fast
has
function to determine whether set has a particular element
Why you may not like sets?
-
Object deduplication is by reference. That seldom happens in the real world - why would I add the same object again in my own logic?
-
I can get the same done in objects - no problem (need no loop, silently fail for duplicates). It has the added advantage of enabling custom logic to avoid duplicates for objects
-
There is no order or an index. I don’t expect anyone to cry on this since sets across languages are purpose built this way. You would have to convert to another collection like an array for indexes (and if you are doing it, are you sure you wanted to begin with a set in the first place?)