How to Convert an Array to a Set in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20211 min read

banner

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.

index.js
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 (...).

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee