3

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?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

3 Answers3

3
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.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • Thank you for your help. I used a combo of your answer plus @Bergi to do this. Choosing answer based on chronology – Doug Fir Apr 01 '15 at 18:47
3

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;
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This is great, thanks a lot. I used the unfancy for loop for now. When I feel more confident in my scripting I'll take a look at filter – Doug Fir Apr 01 '15 at 18:48
1

at first you should convert your NodeList results to an actual array in js and then use the slice method on it.

The best way for converting NodeList to Array is:

myvar = Array.from(myvar);

Now you can use the slice method on your array so easily:

myvar.slice(3,5);
Sara
  • 419
  • 1
  • 6
  • 14