Tutorial by Examples

The Set object lets you store unique values of any type, whether primitive values or object references. You can push items into a set and iterate them similar to a plain JavaScript array, but unlike array, you cannot add a value to a Set if the value already exist in it. To create a new set: cons...
To add a value to a Set, use the .add() method: mySet.add(5); If the value already exist in the set it will not be added again, as Sets contain unique values. Note that the .add() method returns the set itself, so you can chain add calls together: mySet.add(1).add(2).add(3);
To remove a value from a set, use .delete() method: mySet.delete(some_val); This function will return true if the value existed in the set and was removed, or false otherwise.
To check if a given value exists in a set, use .has() method: mySet.has(someVal); Will return true if someVal appears in the set, false otherwise.
You can remove all the elements in a set using the .clear() method: mySet.clear();
You can get the number of elements inside the set using the .size property const mySet = new Set([1, 2, 2, 3]); mySet.add(4); mySet.size; // 4 This property, unlike Array.prototype.length, is read-only, which means that you can't change it by assigning something to it: mySet.size = 5; mySet....
Sometimes you may need to convert a Set to an array, for example to be able to use Array.prototype methods like .filter(). In order to do so, use Array.from() or destructuring-assignment: var mySet = new Set([1, 2, 3, 4]); //use Array.from const myArray = Array.from(mySet); //use destructuring-a...
There are no build-in methods for intersection and difference in Sets, but you can still achieve that but converting them to arrays, filtering, and converting back to Sets: var set1 = new Set([1, 2, 3, 4]), set2 = new Set([3, 4, 5, 6]); const intersection = new Set(Array.from(set1).filter(x...
You can use a simple for-of loop to iterate a Set: const mySet = new Set([1, 2, 3]); for (const value of mySet) { console.log(value); // logs 1, 2 and 3 } When iterating over a set, it will always return values in the order they were first added to the set. For example: const set = new S...

Page 1 of 1