How to Convert an Array to Set in JavaScript

To convert an array to a Set in JavaScript, you can use the “Set()” constructor.

Example 1

let moneyheist = ["Tokyo", "Nairobi", "Berlin", "Oslo", "Moscow"]

let moneyheist_set = new Set(moneyheist)



Set(5) { 'Tokyo', 'Nairobi', 'Berlin', 'Oslo', 'Moscow' }

The new keyword is to create a new set and pass the JavaScript array as its first and only argument. Next, you can see that the array is converted to the Set.

Remember that if your array has repeated values, only one value among the repeated values will be added to your Set. Duplicate values will be removed from the Set because the Set can’t contain duplicates. This can be helpful when you want to get unique values from the array.

Example 2

To preserve the order of the original array and remove duplicates, you can first convert the array to a Set and then convert the Set back to an array using the spread operator.

const myArray = [1, 2, 2, 3, 3, 3];

const mySet = new Set(myArray);
const uniqueArray = [...mySet];



[ 1, 2, 3 ]

In this code, a Set object mySet is created from myArray. The spread operator then converts mySet back to an array with unique values. The resulting uniqueArray contains the unique values in the same order as those in myArray.

Leave a Comment