Collections - Set
Three new Collections: SET(like Array), MAP(Key-Value Object) and WEAKMAP(like Map, but different)
Set object
Set objects are collections of values.
The Set object lets you store unique values of any type.
Basic usage
var mySet = new Set();
mySet.add(1);
mySet.add("firstName");
mySet.add(true);
console.log(mySet); // Set {1, "firstName", true}
console.log(mySet.size); // 3
console.log(mySet.has(1)); // true
mySet.delete("firstName");
console.log(mySet.size); // 2
for (let item of mySet) {
console.log(item);
}
//1
//true
mySet.clear();
console.log(mySet.size); // 0
Unique Values
A value in the Set may only occur once; it is unique in the Set's collection.
var mySet = new Set();
mySet.add(1);
mySet.add(1);
mySet.add(2);
mySet.add("2");
console.log(mySet); // Set {1, 2, "2"}
console.log(mySet.size); // 3
Converting between Array and Set
You can create an Array from a Set using Array.from or the spread operator.
Set objects store unique values, so any duplicate elements from an Array are deleted when converting.
var mySet = new Set([1,2,3,3,true]);
console.log(mySet); // Set {1, 2, 3, true}
var array = Array.from(mySet);
var array1 = [...mySet];
console.log(array); // [1, 2, 3, true]
console.log(array1); // [1, 2, 3, true]
Array Vs Set
- Checking whether an element exists in an collection using indexOf for arrays is slow.
- Set objects let you delete elements by their value. With an array you would have to splice based on a element's index.
- The value NaN cannot be found with indexOf in array.
- Set objects store unique values, you don't have to keep track of duplicates by yourself.