Menü schliessen
Created: September 5th 2024
Last updated: November 29th 2024
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to Convert Iterables to Arrays

Tags:  guide,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In JavaScript, you sometimes receive iterable objects such as Iterators (for example, through Map.prototype.keys()) or NodeList (for example, through document.querySelectorAll()) that aren't arrays. While these have their benefits and reasons to exist within JavaScript, often you'd rather just have an array (perhaps for the convenient helper methods).


The Solution(S)

The currently best supported and most widely applicable solution is using Array.from() like this:

Array.from(iterable)

A new and more convenient solution, which unfortunately isn't baseline available yet, is the chainable toArray() method. It lives on Iterator instances and can be used like so:

iterator.toArray()