Open In App

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 in another array.

These are the following ways we can add an iterator to an array:



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.




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);

Output
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:




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);

Output
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:




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);

Output
Object [Array Iterator] {}
[ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]


Article Tags :