How to Convert ES6 Iterable to Array

Here are two ways to convert ES6 Iterables to Array in JavaScript:

  1. Using Array.from()
  2. Using spread operator

Method 1: Using Array.from()

The Array.from() method is used to create a new array instance from an array-like or iterable object.

Syntax

Array.from(iterableObject[, mapFunction[, thisArg]])

Converting String to Array

const main_str = 'nun2';

const array = Array.from(main_str)

console.log(array)

Output

[ 'n', 'u', 'n', '2' ]

Converting Set to Array

const main_set = new Set([11, 19, 21]);

const array = Array.from(main_set)

console.log(array)

Output

[ 11, 19, 21 ]

Converting Map to Array

const main_map = new Map([[11, 'eleven'], [21, 'twnetlyone']]);

const array = Array.from(main_map)

console.log(array)

Output

[ [ 11, 'eleven' ], [ 21, 'twnetlyone' ] ]

Converting NodeList to Array

const main_node_list = document.querySelectorAll('div');

const array = Array.from(main_node_list)

console.log(array)

Method 2: Using spread operator

You can easily use the spread (…) operator to convert iterables into an array! The spread operator expands an iterable where zero or more arguments or elements are expected.

Spread syntax(…) can be used in combination with an array literal.

Syntax

const newArray = [...iterableObject];

Converting String to Array

const main_str = 'nun2';

const array = [...main_str]

console.log(array)

Converting Set to Array

const main_set = new Set([11, 19, 21]);

const array = [... main_set]

console.log(array)

Output

[ 11, 19, 21 ]

Converting Map to Array

const main_map = new Map([[11, 'eleven'], [21, 'twnetlyone']]);

const array = [... main_map]

console.log(array)

Output

[ [ 11, 'eleven' ], [ 21, 'twnetlyone' ] ]

Converting NodeList to Array

const main_node_list = document.querySelectorAll('div');

const array = [... main_node_list]

console.log(array)

Conclusion

Both methods Array.from() and Spread operator, are helpful in converting iterables to arrays, and the choice between the two often comes down to the specific requirements of your code.

So when choosing between the two, if you are dealing with an iterable, either method will work. However, if you are dealing with an array-like object that is not iterable, Array.from() is the way to go.

Related posts

Set to Array

Map to Array

CSV to Array