JavaScript set to Array | Simple example code

Simplest way to convert set to Array is just spread the set inside [].

Other way convert set to Array in JavaScript:-

  • Array.from() method
  • Spread operator
  • forEach

Example of convert set to Array in JavaScript

Let’s see the one by one HTML example code for each method:-

1. Array.from() method

This method returns an Array object from any object with a length property or an Iterable object.

<!DOCTYPE html> 
<html>  
<body> 

    <script> 
        const set1 =  new Set(['A', 'B', 'C']); 

        console.log(set1);
        console.log(Array.from(set1)); 
    </script> 
    
</body> 

</html> 

Output:

JavaScript set to Array from method

2. Spread operator (…)

The spread operator is commonly used to make shallow copies of JS objects.

<!DOCTYPE html> 
<html>  
<body> 

    <script> 
        const set1 =  new Set(['A', 'B', 'C']); 

        const array1 = [...set1];
        console.log(array1); 
    </script> 
    
</body> 

</html> 

Output: Array(3) [ “A”, “B”, “C” ]

3. forEach method

The forEach() method calls a function once for each element in an array, in order.

<!DOCTYPE html> 
<html>  
<body> 

    <script> 
        const set1 =  new Set([1, 2, 3]); 
        var array1 = []; 

        var ArryFunction = function(val1) { 
            array1.push(val1); 
        }; 

        set1.forEach(ArryFunction); 

        console.log(array1); 
    </script> 
    
</body> 

</html> 

Output: Array(3) [ 1, 2, 3 ]

Q: Is there a simple way to convert Set into Array?

Answer: Yes, Just use Array.from method or spread syntax.

const state =  new Set( [5, 10, 15, 20, 30, 45, 60] );
console.log(Array.from(state));
console.log([...state]);

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.