How to Convert an Array to a Set in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 is 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 to an array, 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 of the Set into the new array.

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

If you need to convert an array of objects to a Set containing only the values of a specific property, use the Array.map() method.

index.js
const arr = [ {id: 1, letter: 'a'}, {id: 2, letter: 'b'}, {id: 3, letter: 'c'}, ]; const set = new Set(arr.map(obj => obj.letter)); // 👇️ Set(3) { 'a', 'b', 'c' } console.log(set);

The function we passed to the Array.map method gets called with each element (object) in the array.

On each iteration, we access the letter property on the object and return the result.

index.js
const arr = [ {id: 1, letter: 'a'}, {id: 2, letter: 'b'}, {id: 3, letter: 'c'}, ]; // 👇️ ['a', 'b', 'c'] console.log(arr.map(obj => obj.letter)); const set = new Set(arr.map(obj => obj.letter)); // 👇️ Set(3) { 'a', 'b', 'c' } console.log(set);

The last step is to pass the array of values to the Set() constructor.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.