Stefano Stefano - 17 days ago 5x
Javascript Question

Transforming a Javascript iterator into an array

I'm trying to use the new Map object from Javascript EC6, since it's already supported in the latest Firefox and Chrome versions.

But I'm finding it very limited in "functional" programming, because it lacks classic map, filter etc. methods that would work nicely with a

[key, value]
pair. It has a forEach but that does NOT returns the callback result.

If I could transform its
from a MapIterator into a simple Array I could then use the standard
with no additional hacks.

Is there a "good" way to transform a Javascript Iterator into an Array?
In python it's as easy as doing
... but
return an array with the Iterator as its first element!!!


I forgot to specify I'm looking for an answer which works wherever Map works, which means at least Chrome and Firefox (Array.from does not work in Chrome).


I know there's the fantastic wu.js but its dependency on traceur puts me off...


You are looking for the new Array.from function which converts arbitrary iterables to array instances:

var arr = Array.from(map.entries());

It is now supported in Edge, FF, Chrome and Node 4+.

Of course, it might be worth to define map, filter and similar methods directly on the iterator interface, so that you can avoid allocating the array. You also might want to use a generator function instead of higher-order functions:

function* map(iterable) {
    var i = 0;
    for (var item of iterable)
        yield yourTransformation(item, i++);
function* filter(iterable) {
    var i = 0;
    for (var item of iterable)
        if (yourPredicate(item, i++))
             yield item;