DEV Community

Matthew Clark
Matthew Clark

Posted on

4 2

Converting an iterable to an array in JavaScript?

JavaScript ES6 introduced, among many other things, the spread operator (...)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax], which allows an iterable to be expanded in places where zero or more arguments or elements are expected.

We can use the spread operator to convert iterables or, as they are sometimes referred to, array-likes. Let's take a look at some examples:

String

When the spread operator is applied to a string, the result is an array of strings each one representing a character of the original string:

const name = 'Zelda';
const letters = [...name]; // 'Z', 'e', 'l', 'd', 'a'
Enter fullscreen mode Exit fullscreen mode

Set

A Set is a collection of unique values. When the spread operator is applied to it, the result is an array of the stored values:

const data = [1, 2, 3, 1, 2, 4]
const values = new Set(data);
const uniqueValues = [...values]; // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Note that the above example is the basis for the uniqueElements snippet[https://www.30secondsofcode.org/js/s/unique-elements].

NodeList

A NodeList is a collection of nodes, returned by methods such as document.childNodes() or document.querySelectorAll(). While it implements some methods that help manipulate it as an array (e.g. NodeList.prototype.forEach()), it's oftentimes desirable to convert it to an array. When the spread operator is applied to it, the result is an array of the contained nodes:

const nodes = document.childNodes;
const nodeArray = [...nodes]; // [ <!DOCTYPE html>, html ]
Enter fullscreen mode Exit fullscreen mode

Note that the above example is the basis for the nodeListToArray snippet[https://www.30secondsofcode.org/blog/s/js/s/node-list-to-array].

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay