How to transform a JavaScript iterator into an array ?
Last Updated :
02 Jul, 2024
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:
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);
OutputObject [Array Iterator] {}
After the conversion the array becomes
[ 'Geeks', 'for', 'Geeks' ]
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);
OutputObject [Array Iterator] {}
[ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]
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);
OutputObject [Array Iterator] {}
[ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]
Using a for...of Loop
To transform a JavaScript iterator into an array using a for...of loop, initialize an empty array, then iterate over the iterator with the loop, pushing each value into the array. This method is straightforward and compatible with all iterable objects.
Example: In this example we defines a generator function that yields numbers 1, 2, and 3. It creates an iterator from the generator and transforms it into an array using a loop. Finally, it logs the array.
JavaScript
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}
const iterator = generateNumbers();
const array = [];
for (const value of iterator) {
array.push(value);
}
console.log(array);
Using map()
Using map() to transform a JavaScript iterator into an array involves converting the iterator to an array with Array.from(), then applying map() to process each element. This method is efficient and allows further transformation if needed.
Example: In this example we converts a Set's iterator to an array using Array.from() and maps each value to itself, resulting in [1, 2, 3]
JavaScript
const iterator = new Set([1, 2, 3]).values();
const array = Array.from(iterator).map(value => value);
console.log(array);
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read