How to Convert an Array to a Set in JavaScript


Borislav Hadzhiev

Tue Oct 19 20211 min read


Photo by Yaoqi

Convert an Array to Set in JavaScript #

To convert an Array to a Set in JavaScript, pass the array as a parameter to the Set() constructor - new Set(arr). The Set constructor is used to create Set objects, that store unique values.

const arr = ['a', 'a', 'b', 'c', 'c']; // 👇️ {'a', 'b', 'c'} const set = new Set(arr); console.log(set.size); // 👉️ 3 console.log(set.has('c')); // 👉️ true

The Set object only stores unique values. Even if the supplied array contains duplicates, they don't get added to the Set.

The only parameter the Set constructor takes in an iterable.

When you pass an array to the Set constructor, all of the array's elements get added to the Set (without the duplicates).

If you need to convert the Set back into an array, you can use the spread operator (...).

const arr = ['a', 'a', 'b', 'c', 'c']; // 👇️ {'a', 'b', 'c'} const set = new Set(arr); const newArr = [...set]; // 👇️ ['a', 'b', 'c'] console.log(newArr);

The spread operator (...) unpacks the values from the Set into the new array.

Note that all of the duplicate values the old array had, will not be contained in the new array.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.