The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

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

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

2:19
`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.
Watch this lesson now
Avatar
egghead.io

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.

Avatar
Brian

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).

Avatar
Hozefa

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

In reply to Brian
Avatar
Trevor

@hozefa That is a great option as well :)

In reply to Hozefa
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?