javascriptarraysfilterecmascript-6nodelist

Filter or map nodelists in ES6


What is the most efficient way to filter or map a nodelist in ES6?

Based on my readings, I would use one of the following options:

[...nodelist].filter

or

Array.from(nodelist).filter

Which one would you recommend? And are there better ways, for example without involving arrays?


Solution

  • Your two examples will be identical if NodeList.prototype[Symbol.iterator] exists, because both cases cover iterables. If your environment has not been configured such that NodeList is iterable however, your first example will fail, and the second will succeed. Babel currently does not handle this case properly.

    So if your NodeList is iterable, it is really up to you which you use. I would likely choose on a case-by-case basis. One benefit of Array.from is that it takes a second argument of a mapping function, whereas the first [...iterable].map(item => item) would have to create a temporary array, Array.from(iterable, item => item) would not. If you are not mapping the list however, it does not matter.