Skip to content
Advertisement

Transforming a Javascript iterable 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 map.entries() from a MapIterator into a simple Array I could then use the standard .map, .filter 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 list(iterator)… but Array(m.entries()) return an array with the Iterator as its first element!!!

EDIT

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).

PS.

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

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement