6
122

JavaScript: How to Iterate through JavaScript Set

Reading Time: 2 minutes

There are 4 methods that are commonly use to iterate through JavaScript Set and we will be discussing them here.

Methods to Iterate

  • Pre ES6 Style
  • Basic array looping style
  • Looping with For...of
  • Looping with ForEach

Before we go into the details, we have a more in-dept post here on how to create and use JavaScript Set for basic understanding.

Pre ES6 Style

Since JavaScript Set is only provided on ES6, we will illustrate a Set concept with an array. Hence, in order to iterate, it is the same as how we iterate array.

// Create a array with unique values
var nameSet = ['Person1', 'Person2', 'Person3'];

// Iterating basic array
for (var i in nameSet){
  console.log(nameSet[i]);  
} 

Basic array looping style

For this method, after we define a Set, we will assign the data to an Array datatype. Then loop over it similar as to an array.

// Create a set to iterate over
const nameSet = new Set(['Person1', 'Person2', 'Person3']);
const nameSetArray = Array.from(nameSet);

// Iterating basic array
for (var i in nameSetArray){
  console.log(nameSetArray[i]);  
} 

Looping with For...of

Set as a built-in object has provided 2 methods to access its attribute. More information in MDN documentation. Hence, we will be able to select one of them that is best for your use case.

  • Set.prototype.entries() -> return iterable of keys and values
  • Set.prototype.values() -> return iterable of values

Let’s look at an illustration on how to use each type of iteration below.

// Create a set to iterate over
const nameSet = new Set(['Person1', 'Person2', 'Person3']);

// Via Set.prototype.entries()
for (const [key, value] of nameSet.entries()) {
  console.log(value);
}

// Via Set.prototype.values()
for (const value of nameSet.values()){
  console.log(value);
}

// Via set reference
for (const value of nameSet) {
  console.log(value); // logs 1, 2 and 3
}

From the looks of each iteration type, the easiest way to loop through JavaScript Set if via the reference. Although nameSet.entries() and nameSet.values() function does seems redundant, it will make the code readable.

Looping with ForEach

forEach method is similar to Set.prototype.entries() since it can also easily retrieve value from the Set iterations.

// Create a set to iterate over
const nameSet = new Set(['Person1', 'Person2', 'Person3']);

// Use forEach to loop through Set
nameSet.forEach(function(value){
  console.log(value);
});

Conclusion

We have look into the 4 methods to iterate through a Javascript Set. Depends on the use case, we may choose any one of them.

Pre ES6 style should only be use if you are supporting older browsers. But with the help of transpiler like babel, we can use For...of or ForEach to iterate through Sets.

Show Comments

No Responses Yet

Leave a Reply