Convert ES6 Iterable to Array

Michael Bylstra picture Michael Bylstra · Dec 23, 2014 · Viewed 56.2k times · Source

Say you have an array-like Javascript ES6 Iterable that you know in advance will be finite in length, what's the best way to convert that to a Javascript Array?

The reason for doing so is that many js libraries such as underscore and lodash only support Arrays, so if you wish to use any of their functions on an Iterable, it must first be converted to an Array.

In python you can just use the list() function. Is there an equivalent in ES6?

Answer

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · Apr 8, 2015

You can use Array.from or the spread operator.

Example:

let x = new Set([ 1, 2, 3, 4 ]);

let y = Array.from(x);
console.log(y); // = [ 1, 2, 3, 4 ]

let z = [ ...x ];
console.log(z); // = [ 1, 2, 3, 4 ]