Get every nth element in an array

I have an array of HTML elements. I check if the previous object exists in the array as follows:

var boxes = $('.box'); // creating the array boxes.each(function(i){ // going through the array var prevBox = i>0?$(boxes[i-1]):false; // check whether a previous box exists if (prevBox) { } // do something else { } // do something else }); 

It works well. But I will also need to check the existence of every fourth object (field) in the array, or rather, whether the object exists three objects before the current one.

This does not work:

 var prevBox = i>0?$(boxes[i-4]):false; 

I believe that using jQuery.grep() and checking if (i % 4) == 0 be the answer, but with my limited knowledge of Javascript, I don’t know how to apply it to what I have.

Can anybody help? Thanks!

+7
source share
3 answers

You can use the module module in a loop to find out if you are in the fourth interval.

Question clarified.

 var boxes = $('.box'); // creating the array boxes.each(function(i){ if( i >= 3 ) { var prevBox = boxes.eq( i - 3 ); var pos = prevBox.position(); var top = pos.top; } }); 
+3
source

Can't you use a for loop?

 for ( var i=0; i< boxes.length; i+=4 ) { // do stuff with boxes[i] } 

I am not big jQuery, but in normal JavaScript that will work fine.

EDIT: You changed the problem a bit, so you want to act on each element, but do something specific on the fourth ...

 var previousTop; for ( var i=0; i< boxes.length; i++ ) { // do stuff with boxes[i] if ( ( (i+1) % 4 ) === 0 ) { previousTop = boxes[i].position.top; // do stuff with the fourth item } } 

Here, the wider scope of previousTop then set every fourth element before doing whatever you need. Then, when you reach the next fourth element, you have the value from the previous in your temporary variable, which looks like what you are looking for, from your answer to @patrick dw below.

+16
source

Use iteration with 4 as an increment, not a regular one.

+1
source

All Articles