hannu
hannu

Reputation: 73

Get every nth item in array

I have an array of HTML elements. I'm checking whether a previous object in the array exists like this:

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
});

This works well. But I would also need to check the existence of every fourth object (box) in the array, or more precisely whether an object three objects before the current one exists.

This doesn't work:

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

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

Anyone can help? Thanks!

Upvotes: 7

Views: 24710

Answers (3)

user113716
user113716

Reputation: 322622

You can use the modulus operator in the loop to see if you are on a fourth interval.

Question was 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;
    }
});

Upvotes: 3

glenatron
glenatron

Reputation: 11382

Can you not just use a for loop?

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

I'm not big on JQuery specifically, but in regular JavaScript that would work fine.

EDIT: You've redescribed the problem somewhat, so you want to act on every item, 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 more broadly scoped previousTop is then being set every fourth item before you do whatever else you need to do. Then when you reach the next fourth element you have the value from the previous one in your temporary variable, which sounds similar to what you are looking for from your response to @patrick dw's answer below.

Upvotes: 16

developer
developer

Reputation: 53

Use an iteration with 4 as the incrementing step and not the usual 1.

Upvotes: 1

Related Questions