array from set javascript

Array from Set JavaScript

If you're working with JavaScript, you'll often find yourself needing to convert a set into an array. Luckily, there's a simple solution: the Array.from() method. This method creates a new array instance from an array-like or iterable object, such as a set.

Using Array.from()

To use Array.from(), simply pass in the set you want to convert as the first argument:


const mySet = new Set(['apple', 'banana', 'orange']);
const myArray = Array.from(mySet);
console.log(myArray); // Output: ['apple', 'banana', 'orange']

As you can see, Array.from() creates an array with the same values as the original set. You can then manipulate this array just like any other:


const mySet = new Set(['apple', 'banana', 'orange']);
const myArray = Array.from(mySet);
myArray.push('peach');
console.log(myArray); // Output: ['apple', 'banana', 'orange', 'peach']

Alternative Solution

If you don't want to use Array.from(), you can use the spread operator (...) to convert a set into an array:


const mySet = new Set(['apple', 'banana', 'orange']);
const myArray = [...mySet];
console.log(myArray); // Output: ['apple', 'banana', 'orange']

This works because the spread operator expands an iterable object, such as a set, into individual elements.

Conclusion

Converting a set into an array is a common task in JavaScript, and Array.from() and the spread operator both provide simple solutions. Whether you prefer one over the other is up to you, but both should work just fine.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe