A JavaScript iterator can be converted into an array by consuming its values and storing them in a new array.
- Use Array.from() or the spread operator for concise solutions.
- Use for...of when you need more control over each value.
- The iterator is consumed during conversion, so it cannot be reused afterward.
Approach 1: Using Symbol.iterator Property
The Symbol.iterator property can create an iterator from an array. The iterator can then be traversed using a for...of loop and its values can be added to a new array.
const array = ['Geeks', 'for', 'Geeks'];
let p = [];
const it = array[Symbol.iterator]();
for (let word of it) {
p.push(word);
}
console.log(p);
Output
[ 'Geeks', 'for', 'Geeks' ]
Approach 2: Using Array.from() Method
The Array.from() method creates a new array from an iterable or array-like object, including JavaScript iterators.
const array = ['Geeks', 'for', 'Geeks'];
const it = array.entries();
const newArr = Array.from(it);
console.log(newArr);
Output
[ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]
Approach 3: Using Spread Operator
The spread operator can expand the values of an iterator into a new array.
const array = ['Geeks', 'for', 'Geeks'];
const it = array.entries();
const newArr = [...it];
console.log(newArr);
Output
[ [ 0, 'Geeks' ], [ 1, 'for' ], [ 2, 'Geeks' ] ]
Approach 4: Using for...of Loop
A for...of loop can iterate through the values of an iterator and add them to an array. This approach is useful when additional processing is required for each value.
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}
const iterator = generateNumbers();
const array = [];
for (const value of iterator) {
array.push(value);
}
console.log(array);
Output
[ 1, 2, 3 ]
Approach 5: Using map()
The map()Â method can be used after converting an iterator into an array with Array.from(). This approach is useful when the iterator values also need to be transformed.
const iterator = new Set([1, 2, 3]).values();
const array = Array.from(iterator).map(value => value);
console.log(array);
Output
[ 1, 2, 3 ]