Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

given an iterator, what's the best way to create an Array?

for example,

let map = new Map();
map.set( 'key1', 'data' );
map.set( 'key2', 'more data' );
...
// now, wish to have an array of keys
let arr = //??// map.keys()  //??//

I could do something lame like

function iter2array( iter ) {
  let arr = new Array();
  for( let e in iter ) arr.push(e);
  return arr;
}

but there has to be a better way.

share|improve this question
    
Please remember an iterator can be infinite. –  jfriend00 7 mins ago

1 Answer 1

Array.from(map.keys()) // ['key1', 'key2']

The Array.from() method creates a new Array instance from an array-like or iterable object.

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.