Sets are one of the new feature added to JavaScript from ECMAScript (ES6) standards. They are very much similar to the popular Arrays but different in many aspects.
As a JavaScript set is similar to an array, we may want to convert it into an array for various requirements.
Though we are unable to use a JavaScript Set like an array (one of the reason being the sets do not have an index), many methods or operators that are available with arrays are available with Sets also. Here we will see, how to convert a set to an Array in different ways.
Suppose we have a set like below
Way 1: By using Array.from()
We can use the new method ‘from’ which will be available on Arrays from ES6. The ‘from’ method returns an array from the passed iterable (in our case, we pass a Set)
Way 2: By using Spread Operator(…)
We can also use the spread operator on the new JavaScript Sets just like the way we use them on arrays or objects
Way 3: By using forEach method
The forEach method which we commonly use on arrays is also available with Sets in JavaScript
Way 4: By using the For..of method
Since for..of do not need any index, we can use this also to iterate through a Set.
We cannot use for..in loop or the ‘concat’ method on Sets which are available on arrays.
Leave A Comment