How to useArray.from() and for loop Methods in JavaScript
In this approach, we will use an array.from() method to convert the set into an array and then we iterate using the for loop.
Example: This example shows the implementation of above-explained approach.
// Initialize a Set object
// using Set() constructor
let myset = new Set()
// Insert new elements in the
// set using add() method
myset.add(3);
myset.add(2);
myset.add(9);
myset.add(6);
// Print the values stored in set
console.log(myset);
const myArray = Array.from(myset);
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Output
Set(4) { 3, 2, 9, 6 } 3 2 9 6
How to iterate over Set elements in JavaScript ?
Set() objects are groups of distinct values. A set is a collection of unique elements i.e. no element can appear more than once in a set. Because sets in ES6 are ordered, the items of a set can be iterated in the order of insertion. Object and primitive values can both be stored in sets.
We can iterate over the set elements using the following methods in JavaScript:
Table of Content
- Approach 1: Using for…of loop
- Approach 2: Using forEach() Method
- Approach 3: Using Array.from() and for loop Methods
- Approach 4: Using Lodash _.forEach() method
- Approach 5: Using Spread Operator