JavaScript Set
In JavaScript, Set is a collection of unique values. In a Set, each values will occur only once.
Create a Set
In JavaScript, a Set can be created using new Set() constructor.
Example
// Create a Set
const letters = new Set();
// Create a Set with default values
const employeeIds = new Set([1,3,2,4]);
add() method
The add() method is used to add the elements to the set.
Example
let letters = new Set();
letters.add("a");
letters.add("b");
letters.add("c");
Iteration Set() methods
The foreach() mehod is used to iterate through the Set elements.
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
letters.forEach (function(value) {
console.log(value);
})
values() method
The values() method is used to iterate the Set and returns the value of it.
Example
const letters = new Set(["a","b","c"]);
for (const x of letters.values()) {
console.log(x);
}