Convert Set to Array in JavaScript

Convert Set to Array in JavaScript

  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

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

  • Check if Array Contains Value in JavaScript
  • Create Array of Specific Length in JavaScript
  • Convert Array to String in JavaScript
  • Remove First Element From an Array in JavaScript
  • Search Objects From an Array in JavaScript
  • Convert Arguments to an Array in JavaScript
  • Related Article - JavaScript Set

  • Convert Array to Set in JavaScript