JavaScript – Convert Array into Set
To convert an Array into a Set in JavaScript, create a new set using new Set()
and pass the array as argument to the constructor. It returns a new set with the unique elements of the given array.
Syntax
The syntax to convert an Array arr
into a Set using Set() constructor is
</>
Copy
new Set(arr)
Examples
In the following example, we convert an Array of numbers, arr, into a Set using Set() constructor.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
//create set from array
var arr = [1, 2, 3, 4]
var set1 = new Set(arr);
var displayOutput = '';
set1.forEach (function(element) {
displayOutput += element + '\n';
});
document.getElementById('output').innerHTML += displayOutput;
</script>
</body>
</html>
Since Set can store only unique elements, and if there are any duplicate elements in the given array, then the duplicates are ignored, and only unique elements make into the Set.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
//create set from array
var arr = [1, 2, 3, 4, 2, 1, 4]
var set1 = new Set(arr);
var output = '';
set1.forEach (function(element) {
output += element + '\n';
});
document.getElementById('output').innerHTML += output;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to convert an Array into a Set in JavaScript using Set() constructor, with examples.