How to Convert Set to Array in JavaScript

Shiv Yadav Feb 02, 2024
  1. Convert Set to Array Using Array.from() in JavaScript
  2. Convert Set to Array Using the Spread Operator in JavaScript
  3. Convert Set to Array Using the Set.prototype.forEach() Function in JavaScript
How to Convert Set to Array in JavaScript

In this article, we’ll look at converting a Set to an array in JavaScript.

Convert Set to Array Using Array.from() in JavaScript

  • Array.from() allows you to build Arrays from the following sources:
  • array-like objects (objects with indexed items and a length property); or
  • items that can be iterated (such as Map and Set).

From iterable objects like Set, the Array.from() method can construct shallow-copied Array instances. With ES6, it was added to the Array object. This is how the code would look:

var aa = new Set([1, 3, 5, 7]);
let ar = Array.from(aa);

console.log(ar);

Output:

[1, 3, 5, 7]

Convert Set to Array Using the Spread Operator in JavaScript

The expansion syntax (...) expands iterations, such as array expressions or strings, where zero or more arguments (for function calls) or elements (for array literals) are expected, or zero or more key-value pairs expand to the expected position (for object literals).

You can also use the spread operator to change the Set to an array. The unfold syntax permits the set to be increased wherein an array literal is expected. It, in turn, brought withinside the ES6 specification of JavaScript.

Its utilization is tested below:

var aa = new Set([1, 3, 5, 7]);
let ar = [...aa];

console.log(ar);

Output:

[1, 3, 5, 7]

Convert Set to Array Using the Set.prototype.forEach() Function in JavaScript

Another solution is to add each element of the Set to the array. This can be easily done using the forEach() method, as shown below:

var aa = new Set([1, 3, 5, 7]);
let ar = [];
aa.forEach(k => ar.push(k));

console.log(ar);

The forEach() method executes the provided callback once for each value in the Set object.

Output:

[1, 3, 5, 7]
Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn

Related Article - JavaScript Array

Related Article - JavaScript Set