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 in another array.
These are the following ways we can add an iterator to an array:
- Using Symbol iterator Property
- Using Array.from Method
- Using the Spread Operator
Method 1: Using Symbol iterator Property
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 into another array named “p” with the use of the following code
p.push(word)
where the word is the value corresponding to the array of elements stored in the iterator. After iterating through each of the elements we get our final array where all the values of the iterator get stored in p.
Example: In this example, we will convert a JavaScript iterator to a JavaScript Array.
javascript
const array = [ 'Geeks' , 'for' , 'Geeks' ]; let p = [] const it = array[Symbol.iterator](); console.log(it); for (let word of it) { p.push(word) } console.log( "After the conversion the array becomes" ); console.log(p); |
Object [Array Iterator] {} After the conversion the array becomes [ 'Geeks', 'for', 'Geeks' ]
Method 2: Using Array.from Method
We can transform the javascript iterator into a JavaScript array by using the array.from() method.
Example:
Javascript
const array = [ 'Geeks' , 'for' , 'Geeks' ]; const mp = array.map( function (val) { return val; }) const it = mp.entries(); console.log(it) let newArr=[]; newArr = Array.from(it); console.log(newArr); |
Object [Array Iterator] {} [ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]
Method 3: Using the Spread Operator
We can transform the javascript iterator into a JavaScript array by using the spread operator method
Example:
Javascript
const array = [ 'Geeks' , 'for' , 'Geeks' ]; const mp = array.map( function (val) { return val; }) const it = mp.entries(); console.log(it) const newArr = [...it]; console.log(newArr); |
Object [Array Iterator] {} [ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]