Categories
JavaScript Answers

How to Transform a JavaScript Iterator into a JavaScript Array?

Spread the love

Sometimes, we have an iterator object in our JavaScript code that we want to convert into an array.

In this article, we’ll look at how to transform a JavaScript iterator into a JavaScript array.

Using the Array.from Method

One way to transform JavaScript iterator into a JavaScript array is to use the Array.from static method.

For instance, we can write:

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
])
const arr = Array.from(map.entries());
console.log(arr)

We create a Map instance which has the entries method that returns an iterator that returns the key-value pairs from the map.

Then we pass the returned iterator from the entries method into the Array.from method to return an array of key-value pair arrays from the iterator.

Therefore, the value of arr is:

[
  [
    "a",
    1
  ],
  [
    "b",
    2
  ],
  [
    "c",
    3
  ]
]

Using the Spread Operator

We can do the same thing that Array.from method does with the spread operator.

It also lets us convert iterator objects to arrays.

For instance, we can write:

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
])
const arr = [...map.entries()];
console.log(arr)

to spread the iterator returned by map.entries into an array.

The key-value pair arrays are spread into the arr array.

Therefore, arr is once again:

[
  [
    "a",
    1
  ],
  [
    "b",
    2
  ],
  [
    "c",
    3
  ]
]

which is the same as the previous example.

Conclusion

We can convert JavaScript iterator objects easily into JavaScript arrays with the Array.from method or the spread operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *