Skip to content

JavaScript Array to Set | Simplest Example code

  • by

How to add an array of values to a Set?

Just pass the array to the Set constructor. to convert Array to set in JavaScript.

var set = new Set(arr);

The Set constructor accepts an iterable parameter. The Array object implements the iterable protocol, so it’s a valid parameter.

JavaScript Array to Set Example code

HTML example code converting Array to set, As you know set have unique values. If there is any duplicate value in the Array it will remove from the set.

<!DOCTYPE html> 
<html>  
<body> 

    <script> 
        var arr = [55, 44, 65, 44];
        var set = new Set(arr);

        console.log(set.size);
        
        console.log(set);
    </script> 
    
</body> 

</html> 

Output:

JavaScript Array to Set HTML

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading