252

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

justin.m.chase
  • 13,061
  • 8
  • 52
  • 100
Stefano
  • 18,083
  • 13
  • 64
  • 79

8 Answers8

365

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;
}
Codebling
  • 10,764
  • 2
  • 38
  • 66
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I would expect the callback to receive `(value, key)` pairs and not `(value, index)` pairs. – Aadit M Shah Feb 25 '15 at 12:49
  • 3
    @AaditMShah: What is a key of an iterator? Of course, if you'd iterate a map, you could define `yourTransformation = function([key, value], index) { … }` – Bergi Feb 25 '15 at 12:53
  • An iterator doesn't have a key but a `Map` does have key value pairs. Hence, in my humble opinion, it doesn't make any sense to define general `map` and `filter` functions for iterators. Instead, each iterable object should have its own `map` and `filter` functions. This makes sense because `map` and `filter` are structure preserving operations (perhaps not `filter` but `map` certainly is) and hence the `map` and `filter` functions should know the structure of the iterable objects that they are mapping over or filtering. Think about it, in Haskell we define different instances of `Functor`. =) – Aadit M Shah Feb 25 '15 at 13:01
  • @AaditMShah: In Haskell, the functor instance of Map doesn't know about keys at all :-) There are [many different traverse functions](http://hackage.haskell.org/package/containers-0.5.6.3/docs/Data-Map-Lazy.html#g:13) though. The one that comes closest to default JS's `.map()` method is probable [Sequence's `mapWithIndex`](http://hackage.haskell.org/package/containers-0.5.6.3/docs/Data-Sequence.html#v:mapWithIndex) – Bergi Feb 25 '15 at 13:05
  • I beg to differ. The `Functor` instance of `Map` in Haskell does know about the keys, which is why it has the type `(a -> b) -> Map k a -> Map k b`. The `Functor` instance of `Map` is defined as `instance Functor (Map k) where ...`. Hence, it knows that there's a key but it doesn't know anything about the type of the key. – Aadit M Shah Feb 25 '15 at 13:14
  • @AaditMShah: Of course maps know about their keys, I meant that the mapping function does not get to see the key (because the `Functor` class doesn't know anything about them). – Bergi Feb 25 '15 at 13:19
  • Well, in that case we do have a [`mapWithKey`](http://hackage.haskell.org/package/containers-0.5.6.3/docs/Data-Map-Lazy.html#v:mapWithKey) function of the type `(k -> a -> b) -> Map k a -> Map k b` which is similar to JavaScript's `map` function. My only problem with your answer is that you are passing the callback functions of `map` and `filter` an index instead of the actual key. To me it makes more sense to pass it the key and not the index because the index can be recovered using a counter and isn't very helpful anyway. The key of a map OTOH can be used for other purposes. See my answer. – Aadit M Shah Feb 25 '15 at 13:27
  • BTW, when I was talking about the `Functor` type class I was only pointing out that we don't have a general `map` function for all "iterable" objects in Haskell. Instead, we define a specific `map` function for individual "iterable" objects by making them an instance of the `Functor` type class. Similarly, it would be much better if you defined specific `map` and `filter` generator functions for individual iterable objects in JavaScript. For example, for `Map` objects you don't really care about the index. You do however care about its keys. Hence, you need specific instances of `map`. – Aadit M Shah Feb 25 '15 at 13:36
  • @Bergi, I cannot really mark your answer as good because Array.from does not work in Chrome (yet), while Map does... – Stefano Feb 25 '15 at 14:09
  • This is my take for my specific case: http://stackoverflow.com/a/28721418/422670 (added there since this question has been closed as a duplicate). – Stefano Feb 25 '15 at 14:29
  • 1
    @Stefano: You can [shim it](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Polyfill) easily… – Bergi Feb 25 '15 at 16:06
  • take a look at https://www.npmjs.com/package/fluent-iterable it has these and a lot more :) – kataik May 05 '20 at 23:41
  • @kataik It's probably better in these days to use a polyfill for the proposed [iterator helpers](https://github.com/tc39/proposal-iterator-helpers) – Bergi May 06 '20 at 08:45
  • Note that this will make the iterator instantly need to find all values until the end of the set, so if you're using a generator to save memory on a million-item data set, you'll crash the program here. – Incognito Jun 18 '20 at 14:34
  • @Incognito Set? What set? What do you mean by "*instantly need to find all values*"? – Bergi Jun 18 '20 at 14:44
  • I mean if you expect a generator to help you by returning values one-by-one and not building a large array in memory, you will undo this benefit if you use Array.from, because it will force the generator to complete. This might not be obvious to people who are new to the concept or starting out with JS. – Incognito Jun 22 '20 at 12:00
  • 1
    @Incognito Ah ok, sure that's true, but it's just what the question is asking for, not a problem with my answer. – Bergi Jun 22 '20 at 13:09
  • Yes, your answer is good. I just wanted a generic warning here for people searching for examples. – Incognito Jun 22 '20 at 15:51
  • The question was for an iterator, but this answer is for an iterable. – justin.m.chase Aug 11 '21 at 22:19
  • @justin.m.chase Every normal iterator is also an iterable. I just named the parameters `iterable` so that one can see the functions are applicable in more generic cases. – Bergi Aug 11 '21 at 22:42
  • @Bergi, no they're not. `i = [][Symbol.iterator]; [...i] // TypeError; function is not iterable`. In that example `i` is an iterator, which is not iterable. Reading the full text of the original question, the body is talking about iterables and the title is just misleading. I specifically needed to convert an iterator and landed here but the question doesn't match the title. I get it now. – justin.m.chase Aug 13 '21 at 15:45
  • @justin.m.chase No, `i` is not an iterator in your example it's a function (that returns an iterator). If you did `i = [][Symbol.iterator](); [...i]`, it works. – Bergi Aug 13 '21 at 15:53
  • You're right. I typo'd but also I psyched myself out by using typescript like `const i: Iterator = [1,2,3][Symbol.iterator]()` but it turns out that `[][Symbol.iterator]()` returns `IterableIterator` not `Iterator`. Thanks. – justin.m.chase Aug 13 '21 at 18:34
66

[...map.entries()] or Array.from(map.entries())

It's super-easy.

Anyway - iterators lack reduce, filter, and similar methods. You have to write them on your own, as it's more perfomant than converting Map to array and back. But don't to do jumps Map -> Array -> Map -> Array -> Map -> Array, because it will kill performance.

Ginden
  • 5,149
  • 34
  • 68
  • 1
    Unless you have something more substantial, this should really be a comment. In addition, `Array.from` has already been covered by @Bergi. – Aadit M Shah Feb 25 '15 at 13:03
  • 3
    And, as I wrote in my original question, `[iterator]` does not work because in Chrome it creates an array with a single `iterator` element in it, and `[...map.entries()]` is not an accepted syntax in Chrome – Stefano Feb 25 '15 at 14:33
  • 4
    @Stefano [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#compat-desktop) is now accepted syntax in Chrome – Klesun Apr 20 '16 at 04:53
21

A small update from 2019:

Now Array.from seems to be universally available, and, furthermore, it accepts a second argument mapFn, which prevents it from creating an intermediate array. This basically looks like this:

Array.from(myMap.entries(), entry => {...});
nromaniv
  • 665
  • 6
  • 18
  • 2
    since an answer with `Array.from` already exists, this is more suited to be a comment or requested edit to that answer... but thanks! – Stefano Jan 23 '19 at 18:37
  • Technically and performance-wise, `myMap.entries()` does create an intermediate array. Not sure if this is prettier or faster than `[...myMap.entries].filter(...)` – Frank N Feb 02 '23 at 10:10
20

There's no need to transform a Map into an Array. You could simply create map and filter functions for Map objects:

function map(functor, object, self) {
    var result = new Map;

    object.forEach(function (value, key, object) {
        result.set(key, functor.call(this, value, key, object));
    }, self);

    return result;
}

function filter(predicate, object, self) {
    var result = new Map;

    object.forEach(function (value, key, object) {
        if (predicate.call(this, value, key, object)) result.set(key, value);
    }, self);

    return result;
}

For example, you could append a bang (i.e. ! character) to the value of each entry of a map whose key is a primitive.

var object = new Map;

object.set("", "empty string");
object.set(0,  "number zero");
object.set(object, "itself");

var result = map(appendBang, filter(primitive, object));

alert(result.get(""));     // empty string!
alert(result.get(0));      // number zero!
alert(result.get(object)); // undefined

function primitive(value, key) {
    return isPrimitive(key);
}

function appendBang(value) {
    return value + "!";
}

function isPrimitive(value) {
    var type = typeof value;
    return value === null ||
        type !== "object" &&
        type !== "function";
}
<script>
function map(functor, object, self) {
    var result = new Map;

    object.forEach(function (value, key, object) {
        result.set(key, functor.call(this, value, key, object));
    }, self || null);

    return result;
}

function filter(predicate, object, self) {
    var result = new Map;

    object.forEach(function (value, key, object) {
        if (predicate.call(this, value, key, object)) result.set(key, value);
    }, self || null);

    return result;
}
</script>

You could also add map and filter methods on Map.prototype to make it read better. Although it is generally not advised to modify native prototypes yet I believe that an exception may be made in the case of map and filter for Map.prototype:

var object = new Map;

object.set("", "empty string");
object.set(0,  "number zero");
object.set(object, "itself");

var result = object.filter(primitive).map(appendBang);

alert(result.get(""));     // empty string!
alert(result.get(0));      // number zero!
alert(result.get(object)); // undefined

function primitive(value, key) {
    return isPrimitive(key);
}

function appendBang(value) {
    return value + "!";
}

function isPrimitive(value) {
    var type = typeof value;
    return value === null ||
        type !== "object" &&
        type !== "function";
}
<script>
Map.prototype.map = function (functor, self) {
    var result = new Map;

    this.forEach(function (value, key, object) {
        result.set(key, functor.call(this, value, key, object));
    }, self || null);

    return result;
};

Map.prototype.filter = function (predicate, self) {
    var result = new Map;

    this.forEach(function (value, key, object) {
        if (predicate.call(this, value, key, object)) result.set(key, value);
    }, self || null);

    return result;
};
</script>

Edit: In Bergi's answer, he created generic map and filter generator functions for all iterable objects. The advantage of using them is that since they are generator functions, they don't allocate intermediate iterable objects.

For example, my map and filter functions defined above create new Map objects. Hence calling object.filter(primitive).map(appendBang) creates two new Map objects:

var intermediate = object.filter(primitive);
var result = intermediate.map(appendBang);

Creating intermediate iterable objects is expensive. Bergi's generator functions solve this problem. They do not allocate intermediate objects but allow one iterator to feed its values lazily to the next. This kind of optimization is known as fusion or deforestation in functional programming languages and it can significantly improve program performance.

The only problem I have with Bergi's generator functions is that they are not specific to Map objects. Instead, they are generalized for all iterable objects. Hence instead of calling the callback functions with (value, key) pairs (as I would expect when mapping over a Map), it calls the callback functions with (value, index) pairs. Otherwise, it's an excellent solution and I would definitely recommend using it over the solutions that I provided.

So these are the specific generator functions that I would use for mapping over and filtering Map objects:

function * map(functor, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        yield [key, functor.call(that, value, key, entries)];
    }
}

function * filter(predicate, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key    = entry[0];
        var value  = entry[1];

        if (predicate.call(that, value, key, entries)) yield [key, value];
    }
}

function toMap(entries) {
    var result = new Map;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        result.set(key, value);
    }

    return result;
}

function toArray(entries) {
    var array = [];

    for (var entry of entries) {
        array.push(entry[1]);
    }

    return array;
}

They can be used as follows:

var object = new Map;

object.set("", "empty string");
object.set(0,  "number zero");
object.set(object, "itself");

var result = toMap(map(appendBang, filter(primitive, object.entries())));

alert(result.get(""));     // empty string!
alert(result.get(0));      // number zero!
alert(result.get(object)); // undefined

var array  = toArray(map(appendBang, filter(primitive, object.entries())));

alert(JSON.stringify(array, null, 4));

function primitive(value, key) {
    return isPrimitive(key);
}

function appendBang(value) {
    return value + "!";
}

function isPrimitive(value) {
    var type = typeof value;
    return value === null ||
        type !== "object" &&
        type !== "function";
}
<script>
function * map(functor, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        yield [key, functor.call(that, value, key, entries)];
    }
}

function * filter(predicate, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key    = entry[0];
        var value  = entry[1];

        if (predicate.call(that, value, key, entries)) yield [key, value];
    }
}

function toMap(entries) {
    var result = new Map;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        result.set(key, value);
    }

    return result;
}

function toArray(entries) {
    var array = [];

    for (var entry of entries) {
        array.push(entry[1]);
    }

    return array;
}
</script>

If you want a more fluent interface then you could do something like this:

var object = new Map;

object.set("", "empty string");
object.set(0,  "number zero");
object.set(object, "itself");

var result = new MapEntries(object).filter(primitive).map(appendBang).toMap();

alert(result.get(""));     // empty string!
alert(result.get(0));      // number zero!
alert(result.get(object)); // undefined

var array  = new MapEntries(object).filter(primitive).map(appendBang).toArray();

alert(JSON.stringify(array, null, 4));

function primitive(value, key) {
    return isPrimitive(key);
}

function appendBang(value) {
    return value + "!";
}

function isPrimitive(value) {
    var type = typeof value;
    return value === null ||
        type !== "object" &&
        type !== "function";
}
<script>
MapEntries.prototype = {
    constructor: MapEntries,
    map: function (functor, self) {
        return new MapEntries(map(functor, this.entries, self), true);
    },
    filter: function (predicate, self) {
        return new MapEntries(filter(predicate, this.entries, self), true);
    },
    toMap: function () {
        return toMap(this.entries);
    },
    toArray: function () {
        return toArray(this.entries);
    }
};

function MapEntries(map, entries) {
    this.entries = entries ? map : map.entries();
}

function * map(functor, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        yield [key, functor.call(that, value, key, entries)];
    }
}

function * filter(predicate, entries, self) {
    var that = self || null;

    for (var entry of entries) {
        var key    = entry[0];
        var value  = entry[1];

        if (predicate.call(that, value, key, entries)) yield [key, value];
    }
}

function toMap(entries) {
    var result = new Map;

    for (var entry of entries) {
        var key   = entry[0];
        var value = entry[1];

        result.set(key, value);
    }

    return result;
}

function toArray(entries) {
    var array = [];

    for (var entry of entries) {
        array.push(entry[1]);
    }

    return array;
}
</script>

Hope that helps.

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • it does thanks! Giving the good answer mark to @Bergi though because I didn't know the "Array.from" and that's the most to the point answer. Very interesting discussion between you too though! – Stefano Feb 25 '15 at 13:57
  • 1
    @Stefano I edited my answer to show how generators can be used to correctly transform `Map` objects using specialized `map` and `filter` functions. Bergi's answer demonstrates the use of generic `map` and `filter` functions for all iterable objects which cannot be used for transforming `Map` objects because the keys of the `Map` object are lost. – Aadit M Shah Feb 25 '15 at 14:31
  • Wow, I really like your edit. I ended up writing my own answer here: http://stackoverflow.com/a/28721418/422670 (added there since this question has been closed as a duplicate) because the `Array.from` does not work in Chrome (while Map and iterators do!). But I can see the approach is very similar and you could just add the "toArray" function to your bunch! – Stefano Feb 25 '15 at 14:31
  • 1
    @Stefano Indeed. I edited my answer to show how to add a `toArray` function. – Aadit M Shah Feb 25 '15 at 14:37
8

You can get the array of arrays (key and value):

[...this.state.selected.entries()]
/**
*(2) [Array(2), Array(2)]
*0: (2) [2, true]
*1: (2) [3, true]
*length: 2
*/

And then, you can easly get values from inside, like for example the keys with the map iterator.

[...this.state.selected[asd].entries()].map(e=>e[0])
//(2) [2, 3]
ValRob
  • 2,584
  • 7
  • 32
  • 40
1

You could use a library like https://www.npmjs.com/package/itiriri that implements array-like methods for iterables:

import { query } from 'itiriri';

const map = new Map();
map.set(1, 'Alice');
map.set(2, 'Bob');

const result = query(map)
  .filter([k, v] => v.indexOf('A') >= 0)
  .map([k, v] => `k - ${v.toUpperCase()}`);

for (const r of result) {
  console.log(r); // prints: 1 - ALICE
}
  • This lib looks amazing & the missing conduit to jump to iterables @dimadeveatii - thanks so much for writing it, I'll try it soon :-) – Angelos Pikoulas Oct 01 '18 at 11:09
1

You can also use fluent-iterable to transform to array:

const iterable: Iterable<T> = ...;
const arr: T[] = fluent(iterable).toArray();
kataik
  • 510
  • 1
  • 5
  • 17
0

Using iter-ops library, you can use filter and map operations directly on the Map, or any iterable object, without converting it into an array:

import {filter, map, pipe} from 'iter-ops';

const m = new Map<number, number>();

m.set(0, 12);
m.set(1, 34);

const r = pipe(
    m,
    filter(([key, value]) => {
        // return the filter flag as required
    }),
    map(([key, value]) => {
        // return the re-mapped value as required
    })
);

console.log([...r]); //=> print all resulting values
vitaly-t
  • 24,279
  • 15
  • 116
  • 138