In JavaScript, you can convert a Set
into an array in the following ways:
- Using
Array.from()
; - Using the Spread Operator;
- Iterating Over the
Set
and Adding Values to an Array.
#Using Array.from()
Array.from()
can be used to create a new, shallow-copied Array
instance from an array-like or iterable object (including Set
). For example:
// ES6+
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
const arr = Array.from(mySet);
console.log(arr); // [1, 2, 3]
#Using the Spread Operator
The spread operator (...
) can be used to unpack iterable objects (such as Set
) into a new array, like so:
// ES6+
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
const arr = [ ...mySet ];
console.log(arr); // [1, 2, 3]
#Iterating Over the Set
and Adding Values to an Array
You can simply iterate over the Set
elements using the Set.prototype.forEach()
method and add each value to an array, for example, like so:
// ES6+
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
const arr = [];
mySet.forEach((item) => arr.push(item));
console.log(arr); // [1, 2, 3]
Since Set
is an iterable object, you may use the for...of
loop as well, for example, like so:
// ES6+
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
const arr = [];
for (const item of mySet) {
arr.push(item)
}
console.log(arr); // [1, 2, 3]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.