How to Convert Array to Set in Javascript?
array to set javascript
const myArray = [1,2,3,1,5,8,1,2,9,4];
const unique = [...new Set(myArray)]; // [1, 2, 3, 5, 8, 9, 4]
const myString = ["a","b","c","a","d","b"];
const uniqueString = [...new Set(myString)]; //["a", "b", "c", "d"]
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>
Output
