JS: the Set Object Tutorial
What is Set Object
New in JS2015.
A βSetβ object are collections of values.
- Value can be any type.
- The values in a set are distinct. (a specific value can occur only once in a set.)
- order of values are maintained, by insertion time.
Creating Set
new Set()
- Create a empty set.
new Set(iterable)
- Create a set from values in iterable object iterable.
const ss = new Set([3, 4, 5]); console.log(ss); // Set { 3, 4, 5 }
Parent of Set Objects
The parent of any set object is Set.prototype
.
Size of Set
Add a Value
Delete a Value
Check Existence
Clear Set
Iteration
Union, Intersection, Difference
Convert Set to Array
Set of Arrays, Set of Objects
Set can contain value of any type. But when elements are objects (or arrays), be careful that two object of same structure and element values is considered different objects.
// set of array // note the array [3] is duplicated, because [3] === [3] returns false const ss = new Set([4, [3], [3]]); console.log(ss); // Set { 4, [ 3 ], [ 3 ] } // note here there the [3] is not duplicated const aa = [3]; const ss2 = new Set([4, aa, aa]); console.log(ss2); // Set { 4, [ 3 ] }
Add Arbitrary Properties to Set
Because set is a object, you can still add arbitrary properties to a set object. (but you shouldn't do it.) γsee Object Typeγ
const ss = new Set([4, 5, 6]); // you can add arbitrary properties to a set object ss.pp = 3; console.log(ss.pp === 3); console.log(ss.hasOwnProperty("pp"));