Converting an array-like object into an Array with Array.from()

Trevor Miller
InstructorTrevor Miller

Share this video with your friends

Send Tweet

Array.from() lets you convert an "iterable" object (AKA an array-like object) to an array. In this lesson, we go over grabbing DOM nodes and turing them into an array so that we can use methods like Array.filter() and Array.forEach() on them.

Brian
Brian
~ 5 years ago

Some more background. NodeList, HTMLCollection, etc. are both Iterable (they implement [Symbol.iterator] on their prototype, and ArrayLike (they have an integer length property). The cool thing about Array.from is that is handles both cases, so anything that you might previously have done [].slice.call(ArrayLike) on is covered, as are Iterables (the result of generators, along with Map, Set, TypedArray, etc)

It turns out that most ArrayLike objects (such as arguments) are also Iterable in ES6, and projects are following suit (e.g. jQuery returns Iterable collections now).

Hozefa
Hozefa
~ 4 years ago

How about doing using spread operator to convert NodeList or HTMLCollection into an array?

Trevor Miller
Trevor Millerinstructor
~ 4 years ago

@hozefa That is a great option as well :)