Skip to content

JavaScript iterable to Array | Example code

  • by

Use ES6 spread (…) to easily convert Iterables into the Array in JavaScript.

const newArr1  = [ ...map  ];

JavaScript Array already is an ES6 iterable. But Often, iterables are limited in terms of their built-in methods. By converting iterable to the array, you’ll have access to ALL of the array methods such as filter, map, and reduce.

JavaScript iterable to Array

Simple example code converts Iterables to Array using Spread.

<!DOCTYPE html>
<html>
<body>
  <div></div>
  <script>

    console.log([ ...'hi' ]);

    console.log([ ...new Set([1,2,3])]); 

    console.log([ ...new Map([[1, 'one']])]); 

    console.log(([ ...document.querySelectorAll('div')])); 
  </script>
</body>
</html>

Output:

JavaScript iterable to Array

If you are working with array-like objects then use Array.from. it takes an iterable as in input and returns an array of the iterable.

const map = new Map([[ 1, 'one' ],[ 2, 'two' ]]);

const newArr1  = [ ...map  ];  // create an Array literal and use the spread syntax on it
const newArr2 = Array.from( map );  // 

console.log(newArr1, newArr2); 

Output: [ [ 1, "one" ], [ 2, "two" ] ] [ [ 1, "one" ], [ 2, "two" ] ]

Do comment if you have any doubts or suggestions on this Js iterable 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