Borislav Hadzhiev
Tue Oct 19 2021·1 min read
Photo by Yaoqi
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.