Skip to content
the poor coder

array from set javascript

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC