Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to transform a JavaScript iterator into an array ?

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.

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


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:

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


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:

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


Output

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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments