How to convert Iterables to Array using Spread in JavaScript?

How to convert Iterables to Array using Spread in JavaScript?

In this post, you'll learn how to 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 🎉

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
};

Array.from(arrayLikeObject); // [ 'a', 'b' ]

[...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 😆


This post was originally published at samanthaming.com

javascript web-development es6

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Progressive Web App Development

Hire Full Stack Developer from HireFullStackDeveloperIndia.com to build user-centric & robust Progress Web App Development Solutions in India.