How to map a JavaScript iterable without writing an iteration function?

Some methods in Javascript, for example Map.prototype.values, return an iterable. Without writing a function to iterate through the values, can I map them to something else as per Array.prototype.map? Is there a way to realize the iterable’s values into an Array object that I can then invoke the map method of?

Or do I have to write something like

function realize(it) {
  let result = Array();
  for (i of it) {
    result.push(i);
  }
  return result;
}

every time I need to do this in js?

>Solution :

If the goal is specifically to map your values to something else, you can use Array.from() with a mapping callback.

Array.from(iterable, x => x * 2);

This prevents having to construct an intermediate array, and having to iterate twice over the values. In terms of both space and time complexity, Array.from() handily beats the combination of spread syntax and Array.prototype.map().

Leave a Reply