Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slice not working as expected on my array

I have an array scraped from a webpage:

myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr')

Which in the console returns an array: enter image description here

What I need to do is subset this array:

  1. Start from the 3rd item
  2. Then keep every odd number of items

So I need a subset of my var with items 3 and 5 in it.

I tried: myvar.slice(3,5). This returned error "Undefined is not a function"

Had I been successful I would have an array with 3 items. I'd then need to subset on keeping odd items in the array.

How do I subset for myvar so that I have a variable with items 3 and 5 left in it? If myvar was length 10. How would I subset it to include items 3, 5, 7, 9?

like image 953
Doug Fir Avatar asked May 06 '26 19:05

Doug Fir


2 Answers

I tried: myvar.slice(3,5). This returned error "Undefined is not a function"

Yes, because querySelectorAll returns a node list and not an array. See also Fastest way to convert JavaScript NodeList to Array?.

How do I subset for myvar so that I have a variable with items 3 and 5 left in it? If myvar was length 10. How would I subset it to include items 3, 5, 7, 9?

You'd need to do that manually anyway, there is no such method in javascript for slicing subsequences with steps. Use

var arr = [],
    myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr');
for (var i=3; i<myvar.length; i+=2)
    arr.push(myvar[i]);

(or, if you want to be fancy)

var arr = Array.prototype.filter.call(document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr'), function(_, i) {
    return i%2==1 && i>2;
});
like image 147
Bergi Avatar answered May 09 '26 09:05

Bergi


myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr')

myvar is a nodeList and it's not an array. So you can't use array functions in there.

But you can use apply or call to get the array functionality on nodelist.

How to get those functionality?

Array.prototype.slice.call(myvar, 3,5);

Now you can use slice in the nodelist.

But for your actual question, to get only subset matching particular criteria is not possible via slice as well.

You must iterate through the elements and do it manually.

like image 29
mohamedrias Avatar answered May 09 '26 08:05

mohamedrias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!