Transforming a Javascript iterable into an array

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;
}

Leave a Comment