Convert Iterables to Array using Spread in JavaScript
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: