Iterating Sets
suggest changeYou can use a for...of loop to iterate a Set. Values come out in insertion order. Adding a value that is already present does not move it.
const mySet = new Set([1, 2, 3]);
for (const value of mySet) {
console.log(value); // logs 1, 2 and 3
}
For example:
const set = new Set([4, 5, 6])
set.add(10)
set.add(5) //5 already exists in the set
Array.from(set) //[4, 5, 6, 10]
There’s also a .forEach() method, similar to Array.prototype.forEach(). It has two parameters, callback, which will be executed for each element, and optional thisArg, which will be used as this when executing callback.
callback has three arguments. The first two arguments are both the current element of Set (for consistency with Array.prototype.forEach() and Map.prototype.forEach()) and the third argument is the Set itself.
mySet.forEach((value, value2, set) => console.log(value)); // logs 1, 2 and 3
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents