1 Introduction
Array like collection objects looks like an JavaScript array, but are not one. They have indexed access
and length property, but they don't have any of Array
methods like map
, filter
etc.
In order to use array method on them, first we need to convert them into an Array
.
Most common example of Array like object are String and the NodeList
and HTMLCollection
collection returned by these
methods -
document.getElementsByClassName
document.getElementsByTagName
document.querySelectorAll
2 Methods to Convert
2.a Using Array.from
method
Array.from
accept an array like or iterable object and returns a shallow copy of it which is an Array
.
const nodes = document.getElementsByTagName('p');
const nodesArray = Array.from(nodes);
2.b Using Spread [...]
operator
Spread operator spread each item of Array like objects into an array.
const nodes = document.getElementsByClassName('cool');
const nodesArray =[...nodes];
2.c Using Array.prototype.slice.call
method
We can call slice
method on Array like objects using call
method, this
will return a new array.
const nodes = document.querySelectorAll('p');
const nodesArray = Array.prototype.slice.call(nodes);
More about call
method Here