Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading