To convert an array to a set in JavaScript we simply just need to pass the array as a parameter when creating a new set, new Set(). One of the main differences between an array and a set is that a set does not contain duplicate values.

var numbers_array = [13, 48, 92, 13, 48, 3, 13, 92];
var numbers_set = new Set(numbers_array);

console.log(numbers_set);

#Output:
{13, 48, 92, 3}

As you can see from the code above, the array, numbers_array, has multiple duplicate values in it. When we create a new set using the array as a parameter, the duplicate values in the array are left out of the set, and only the unique numbers are left.

Let’s take a look at another example below.


Let’s say we have a simple array of colors and we want to convert the array to a set. To do this we simply use the set constructor again, passing it the array of colors.


var arrayOfColors = ["red","blue","green","red","yellow","orange","black","purple","pink","blue","black"];
var color_set = new Set(arrayOfColors);

console.log(set);

In this example, the resulting set, color_set, would now contain the following:

{‘red’, ‘blue’, ‘green’, ‘yellow’, ‘orange’, ‘black’, ‘purple’, ‘pink’}

Hopefully this article has been useful to help you understand how to convert an array to set using JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024