Skip to content
the poor coder

js new array from new set

Poor Man
Published
Reading time
1 min read
On this page

Creating a New Array from a New Set in JavaScript#

If you want to create a new array from a new set in JavaScript, there are a few ways to do it. The most common way is to use the spread operator to convert the set into an array.

Using the Spread Operator#

The spread operator is a new feature in JavaScript that allows you to expand an iterable object into individual elements. In this case, we can use the spread operator to convert the set into an array.

Text
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray); // [1, 2, 3]

In the example above, we create a new set called `mySet` that contains the values 1, 2, and 3. We then use the spread operator to convert the set into an array and assign it to a new variable called `myArray`. Finally, we log the contents of `myArray` to the console.

Using the Array.from() Method#

An alternative way to create a new array from a new set is to use the `Array.from()` method. This method creates a new array from an iterable object.

Text
const mySet = new Set([1, 2, 3]);
const myArray = Array.from(mySet);
console.log(myArray); // [1, 2, 3]

In the example above, we create a new set called `mySet` that contains the values 1, 2, and 3. We then use the `Array.from()` method to create a new array from `mySet` and assign it to a new variable called `myArray`. Finally, we log the contents of `myArray` to the console.

Conclusion#

Creating a new array from a new set in JavaScript is easy and can be accomplished using either the spread operator or the `Array.from()` method. Both methods are equally valid and it's up to personal preference which one you choose to use.

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