Set is a special type collection, like an array where each value may occur only once. Declaration new Set([iterable])
// creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
let set = new Set([1,1,2,2,3,3]);
set // Set(3) {0:1, 1:2, 2:3}
Add
let set = new Set()
let john = { name: "John" }
let pete = { name: "Pete" }
let mary = { name: "Mary" }
set.add(john)
set.add(pete)
set.add(mary)
set.add(john)
set.add(mary)
set // Set(3) {{…}, {…}, {…}}
Get It seems there is no native way. Size
set.size; // 3
Delete set.delete(value) - returns true if value existed at the moment of the call, otherwise false. set.clear() - removes everything from the set
set.delete(john); // true
// but
set.delete({ name: "John" }); // false
set.clear()
set // Set(0) {size: 0}
Has set.has(value) returns true if the value exists in the set, otherwise false
set.has(pete); // true
// but
set.has({ name: "Pete" }); // false
Iteration
set.keys() // returns an iterable object for values, because there are no keys in Set, exists for compatibility with Map.
set.values() // returns an iterable object for values
set.entries() // returns an iterable object for entries [value, value], exists for compatibility with Map.
for (let user of set) {
alert(user.name); // John (then Pete and Mary)
}
set.forEach((value, valueAgain, set) => {
alert(value.name); // John (then Pete and Mary)
});
Set-- > Array
let set = new Set([1,1,2,2,3,3])
set // Set(3) {1, 2, 3}
arr = Array.from(set)
arr // [1, 2, 3]
WeakSet allows to store only objects removes them once they become inaccessible main advantages are that they have weak reference they can easily be removed by garbage collector disadvantages are not having support for clear, size, keys, values… An object exists in the set while it is reachable from somewhere else Like Set, it supports add, has and delete, but not size, keys() and no iterations.
xx let weakSet = new WeakSet();
let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };
weakSet.add(john);
weakSet.add(pete);
weakSet.add(john);
// weakSet has 2 users now
// check if John visited?
alert(weakSet.has(john)); // true
alert(weakSet.has(mary)); // false
john = null;
// weakSet will be cleaned automatically