Iterating over a Set object in JavaScript is a common task.
There are several ways to do it.
Here are some examples of how to iterate over a Set object in JavaScript:
Using a for...of
loop:
The for...of
loop is a new syntax introduced in ECMAScript 6 (ES6) that allows iterating over iterable objects, including Sets.
The basic syntax of the for...of
loop is as follows:
for (let value of iterable) {
// do something with value
}
To iterate over a Set using a for...of
loop, we can simply pass the Set object as the iterable.
Here’s an example:
const mySet = new Set(["apple", "banana", "orange"]);
for (let value of mySet) {
console.log(value);
}
// Output:
// 'apple'
// 'banana'
// 'orange'
In this example, we created a Set object called mySet
containing three string values. We then used a for...of
loop to iterate over the Set and log each value to the console.
Using the forEach
method:
Another way to iterate over a Set in JavaScript is to use the forEach
method. The forEach
method is a built-in method of the Set object that allows executing a callback function for each element in the Set.
The basic syntax of the forEach
method is as follows:
mySet.forEach(callback);
In this syntax, mySet
is the Set object we want to iterate over, and callback
is the function we want to execute for each element in the Set. The callback
function takes two parameters: the current element of the Set, and the index of the current element.
Here’s an example of using the forEach
method to iterate over a Set:
const mySet = new Set(["apple", "banana", "orange"]);
mySet.forEach(function (value) {
console.log(value);
});
// Output:
// 'apple'
// 'banana'
// 'orange'
In this example, we created a Set object called mySet
containing three string values. We then used the forEach
method to iterate over the Set and log each value to the console.
Using the entries
method:
The entries
method is a built-in method of the Set object that returns a new iterator object that contains an array of [value, value]
for each element in the Set. We can use this iterator object to iterate over the Set using a for...of
loop.
Here’s an example of using the entries
method to iterate over a Set:
const mySet = new Set(["apple", "banana", "orange"]);
for (let [value, index] of mySet.entries()) {
console.log(value);
}
// Output:
// 'apple'
// 'banana'
// 'orange'
In this example, we created a Set object called mySet
containing three string values. We then used the entries
method to get an iterator object containing [value, value]
arrays for each element in the Set. Finally, we used a for...of
loop to iterate over the iterator object and log each value to the console.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.