How to transform a JavaScript iterator into an array?

The task is to convert an iterator into an array

This can be performed by iterating each value of the iterator and storing the value into another array 

Method:

To make an iterator for an array:

const it = array[Symbol.iterator](); 

So first we make an iterator for the  “array” named “it”. After creating the iterator we iterate to each value stored in that iterator and push it in another array named “p” with the use of the following code



p.push(word)

where the word is the value corresponding to the array elements stored in the iterator. After iterating through each of the element we get our final array where all the values of the iterator get stored in p.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    const array = ['Geeks', 'for', 'Geeks']; 
    p=[]
    const it = array[Symbol.iterator](); 
    document.write(it);
    document.write("<br>");
  
    for(let word of it)
    {
       p.push(word)
    }
document.write(
"After the conversion the array becomes");
document.write("<br>");
document.write(p);
</script>

chevron_right


Output:

[object Array Iterator]
After the coversion the array becomes
["Geeks", "for", "Geeks"]

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.