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.forEach() on them.
[00:31] Then let's log these out, see what they contain. So we can see that we have our products and if we open this up, we can see that they are of the type nodelist, and the problem with the nodelist is that it's like an array but it's not an array, so it doesn't have all of the typical array methods that we want to use like filter, and foreach, and reduce. What we can do is we can convert this nodelist into an array, and then we'll be able to use the array methods on the lists.
[00:59] In the past there's been a lot of hackey ways to do this, but now with ECMAScript 2015 we have a native way to do it with the array.from method. So I'm going to go up here and wrap my node list here with array.from. If we log this out, we'll be able to see if we open this up again, that it's now of type array. Now we can use the array methods to solve our original problem of highlighting numbers that are less than 10 in the list.
[01:26] What I'm going to do now is say products, and we'll filter those products, and we'll filter if the product, the number inside of that product, supply parse float and we'll grab the products' innerHTML, and we'll check if it is less than $10. Then when we get that list of the products that are less than $10, we're going to foreach over them, and for each of those products, we're going to say product.style.color and we'll set that equal to red.
[02:07] Now we're highlighting the items that are less than $10. So you can see that being able to convert a nodelist or any other type of iterable collection into an array can be very useful.
Some more background.
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
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).
How about doing using
spread operator to convert
HTMLCollection into an
@hozefa That is a great option as well :)