Skip to content

Convert Set to Array JavaScript

  • by

You can use Array from method, spread operator, or forEach to Convert Set to Array in JavaScript.

Note: safer for TypeScript.

const array = Array.from(mySet);

Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856). It’s safer to use Array.from above instead.

const array = [...mySet];
  • The old-fashioned way, iterating and pushing to a new array (Sets do have forEach):
const array = [];
mySet.forEach(v => array.push(v));
  • Previously, using the non-standard, and now deprecated array comprehension syntax:
const array = [v for (v of mySet)];

Convert Set to Array JavaScript

Simple example code several ways to convert a Set to an Array:

<!DOCTYPE html>
<html>
<body>
  <script>
   var s = new Set([2, 4, 6, 8]);
   
   console.log(Array.from(s));
   console.log([...s])

   let arr = [];
   s.forEach(x => arr.push(x));
   console.log(arr)
 </script>
</body>
</html>

Output:

Convert Set to Array JavaScript

Do comment if you have any doubts or suggestions on this Js Convert Set topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading