Learn Beginner

The fastest way to convert array like object into js array

In this fast programming era every developer face this issue including me. So I am finding best and fastest way to convert array like object into js array.

In this fast programming era every developer face this issue including me. So I am finding best and fastest way to convert array like object into js array.

1. What is the problem?

Suppose you have a list of divs on your page and you query them via document.querySelectorAll.

let rows = document.querySelectorAll('img')
NodeList(11) 

However, rows is not an array that you can manipulate with all of the handy array methods, like map(), filter()etc.

oops, I am not an array, buddy

That is because

NodeList object is a list (collection) of nodes extracted from a document.

So after this the question is “What can We do?”

2. What can I do?

The easiest, fastest way to convert it into an array is just using the es6 spread operator.

let rows = document.querySelectorAll('img');
rows = [...rows]

Now, you can start applying all of the array methods to this rows

get me those images that I want!

3. Other ways to solve the problem here

  1. use es6 spread operator […arrayLikeObject]
  2. usees6 Array.from(arrayLikeObject)
  3. [].slice.call(arrayLikeObject)
  4. use the good old for loop, code snippet is below, feel free to copy it, LOL
let trueArray = []
for(let i = 0; i < rows.length; i++) {
   trueArray.push(rows[i])
}

If you know any other ways, feel free to leave a comment below!

Thanks for reading! ? If you find this helpful don’t forget to give some claps ?? and feel free to share this with your friends and followers! ?If you have some tips to share, feel free to comment below.

Hiren Vaghasiya

Hiren is an avid technical geek and blog lover. Now a high time tech blogger here, along with Freelancer, Web Designer, Digital Marketer & Sales Funnel Specialist.

Add comment

Learn Beginner

Don't be shy, get in touch. We love meeting interesting learners and making the world's best developers.