iterator.toArray()
is equivalent to Array.from(iterator)
and [...iterator]
, except that it's easier to chain when multiple iterator helper methods are involved. The following example creates an iterator that yields terms in the Fibonacci sequence, takes the first 10 terms, filters out the odd numbers, and converts the result to an array:
function* fibonacci() {
let current = 1;
let next = 1;
while (true) {
yield current;
[current, next] = [next, current + next];
}
}
const array = fibonacci()
.take(10)
.filter((x) => x % 2 === 0)
.toArray();
console.log(array);
Note that it's a good idea to call toArray()
as a last step of your processing. For example, fibonacci().take(10).toArray().filter(...)
is less efficient, because iterator helpers are lazy and avoids creating a temporary array.