1

So I can call map() on an array to iterate through it and return another array, like so:

[1,2,3].map( (value, index) => value * index )

What if I want to do the same over a Map object?

var myMap = new Map();
myMap.set(0, 1);
myMap.set(1, 2);
myMap.set(2, 3);

This isn't valid:

myMap.map( (value, index) => value * index )

There's a forEach but that's not the same.

Is there a quick shorthand way to generate an array from a Map, like map() does on an array?

– hopefully that sentence makes sense.

Ben
  • 20,737
  • 12
  • 71
  • 115
  • What do you expect it to return? You accept a key and an index, but return only a scalar value. Is it supposed to be an array as a result? – zerkms Aug 28 '15 at 05:49
  • @zerkms same as the array example – iterates through each element of the map and returns an array of the computed values from the mapped function. resulting array should have the same number of elements as the original map. – Ben Aug 28 '15 at 05:50

1 Answers1

10

If the result must be an array then you can use the Array.from() and Map.prototype.entries():

Array.from(myMap.entries()).map(([key, value]) => key * value)

alternatively you could spread the iterator:

[...myMap.entries()].map(...)
zerkms
  • 249,484
  • 69
  • 436
  • 539