DEV Community

loading...
Cover image for Convert Iterable to Array using Spread

Convert Iterable to Array using Spread

samanthaming profile image Samantha Ming Originally published at samanthaming.com ใƒปUpdated on ใƒป3 min read

Convert Iterables to Array using Spread

CodeTidbit by SamanthaMing.com

Use ES6 spread (...) to easily convert Iterables into an Array! Often, iterables are limited in terms of their built-in methods. By converting it into an array, you'll have access to ALL of the amazing array methods such as filter, map, reduce! Awesome ๐ŸŽ‰

[ ...'hi' ]; // // ['h', 'i']

[ ...new Set([1,2,3]) ]; // [1,2,3]

[ ...new Map([[1, 'one']]) ]; // [[1, 'one']]

[ ...document.querySelectorAll('div') ] // [ div, div, div]

Built-in Iterables

In JavaScript, we have some built-in iterables that we use spread to convert them to an array:

  • String
  • Array
  • Map
  • Set

There's one more, but we won't focus on that for this post, TypedArray.

What are Iterables?

Iterables are data structures which provide a mechanism to allow other data consumers to publicly access its elements in a sequential manner.

If you're interested in learning more about iterables, check out these awesome posts:

String โ†’ Array

const myString = 'hello';

const array = [...myString] // [ 'h', 'e', 'l', 'l', 'o' ]

We can convert the array back to a string by using join()

array.join(''); // 'hello'

Set โ†’ Array

const mySet = new Set([1, 2, 3]);

const array = [...mySet] // [1, 2, 3]

We can convert the array back to a string by passing it into new Set

new Set(array); // Set { 1, 2, 3 }

Map โ†’ Array

const myMap = new Map([[1, 'one'], [2, 'two']]);

const array = [...myMap] // [ [ 1, 'one' ], [ 2, 'two' ] ]

Similar to Set, we can convert the array back to a string by passing it into new Map

new Map(array); // Map { 1 => 'one', 2 => 'two' }

NodeList โ†’ Array

const nodeList = document.querySelectorAll('div');

const array = [ ...document.querySelectorAll('div') ];
// [ div, div, div] *

*I suggest you paste the code into your browser to see the actual output

Array.from vs Spread

Another very similar method to the Spread syntax is Array.from. In fact, we can replace our examples with this:

Array.from('hi') // // ['h', 'i']

Array.from(new Set([1,2,3])) // [1,2,3]

Array.from(new Map([[1, 'one']])) // [[1, 'one']]

Array.from(document.querySelectorAll('div')) // [ div, div, div]

What's the difference?

The difference is in the definition

Array.from works for:

  • array-like objects (objects with a length property and indexed elements)
  • iterable objects

Spread only works for:

  • iterable objects

So let's take a look at this array-like object:

const arrayLikeObject = {
  0: 'a', // indexed element
  1: 'b', // indexed element
  length: 1, // length property
};

// โœ… Using Array.from
Array.from(arrayLikeObject); // [ 'a', 'b' ]

// โŒ Using Spread
[...arrayLikeObject]; // TypeError: arrayLikeObject is not iterable

Which should I use?

Of course, it depends. If you are working with array-like objects, you have no choice but to use Array.from. But when it comes to iterables, I've always used spreads. Why? Because I'm a huge fan of the Airbnb Style guide. I wish I have a better reason, but that's all I have lol ๐Ÿ˜ I'm guessing because it's less typing ๐Ÿค” If you know the reason, please drop it in the comment ๐Ÿ˜†

Community Input

@nickytonline: I like using spread as well, but if you want to e.g. convert a NodeList to an array and then map over it, consider using Array.from. I discovered this summer that Array.from has a second argument which is a map callback function that is called as each item is created.

Resources


Thanks for reading โค
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com

Discussion (6)

pic
Editor guide
Collapse
nickytonline profile image
Nick Taylor (he/him)

I like using spread as well, but if you want to e.g. convert a NodeList to an array and then map over it, consider using Array.from.

I discovered this summer that Array.from has a second argument which is a map callback function that is called as each item is created.

Looking forward to your next post!

Collapse
samanthaming profile image
Samantha Ming Author

That totally is the benefit with Array.from! Awesome point, let me add it to the code notes๐Ÿ˜๐Ÿ‘

Collapse
mateiadrielrafael profile image
Matei Adriel

Whoa, thats awesome

Collapse
mateiadrielrafael profile image
Matei Adriel • Edited

Cant wait to be able to do

const set = new Set([1, 2, 3])
const array = set |> Array.from
Collapse
samanthaming profile image
Samantha Ming Author

Thatโ€™s new syntax for me๐Ÿคฉ...what language is that based from? ๐Ÿ˜ฎ

Collapse
mateiadrielrafael profile image
Matei Adriel

Probably haskell or some other functional lamg