How to Convert Array to Set in JavaScript?
The task is to convert a JavaScript Array to a Set with the help of JavaScript. we’re going to discuss 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 it first and only argument.
- This will automatically create the set of the provided array.
Example 1: In this example, the array is converted into set using the same approach defined above.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Convert Array to Set. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" id = "h1" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ 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 > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2: In this example, the array is converted into set using a bit approach than above.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Convert Array to Set. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" id = "h1" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 15px; font-weight: bold;"> </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </ 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 > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button: