Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Convert Array to Set in JavaScript?

Improve Article
Save Article
  • Last Updated : 19 Jan, 2023
Improve Article
Save Article

The task is to convert a JavaScript Array to a Set with the help of JavaScript. we’re going to discuss a few techniques. 

Approach:

  • Take the JavaScript array into a variable.
  • Use the new keyword to create a new set and pass the JavaScript array as its first and only argument.
  • This will automatically create the set of the provided array.

Example 1: In this example, the array is converted into a set using the same approach defined above. 

html




<h1 style="color:green;" id="h1">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
    var A = [1, 1, 2, 2, 2, 2, 5, 5];
      
    up.innerHTML = "Click on the button to convert"+
    " the array to set.<br>" + "Array - [" + A + "]";
      
    function GFG_Fun() {
        var set = new Set(A);
        down.innerHTML = JSON.stringify([...set]);
    }
</script>

Output:

How to Convert Array to Set in JavaScript?

How to Convert Array to Set in JavaScript?

Example 2: In this example, the array is converted into set using a bit approach than above. 

html




<h1 style="color:green;" id="h1">
    GeeksForGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    var down = document.getElementById('GFG_DOWN');
      
    var A = ["A", "A", "Computer Science", "portal",
            "for", "for", "Geeks", "Geeks"];
      
    up.innerHTML = "Click on the button to convert "+
    "the array to set.<br>" + "Array - [" + A + "]";
      
    function GFG_Fun() {
        var set = new Set(A);
        down.innerHTML = JSON.stringify([...set.keys()]);
    }
</script>

Output:

How to Convert Array to Set in JavaScript?

How to Convert Array to Set in JavaScript?


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!