SoWizardly
SoWizardly

Reputation: 407

Having trouble with a for loop not iterating enough

So I have a problem with this FOR loop that I just can't quite figure out. In this case, I know this needs to iterate as least twice. The array, at a minimum, looks something like this...

    dTrackerArray = {sParentValue, 1234, sParentValue, 5678}

But for some reason this for loop is only removing one instance instead of all of them.

     var check = $.inArray(sParentValue, dTrackerArray);
      if (check != -1) {
       for(var i = dTrackerArray.length; i > 0; i--) {
         if( dTrackerArray[i] === sParentValue ) {
          dTrackerArray.splice(i,1);
          dTrackerArray.splice(i-1,1);
          }

      }}

I really appreciate any help I can get here! Thanks!

EDIT: The 2nd splice is to remove the 1234 "associated" with the sParentValue. It seems to work ok.

Upvotes: 4

Views: 118

Answers (3)

Jaaromy Zierse
Jaaromy Zierse

Reputation: 569

Easy to miss but you need i >= 0.

EDIT: Although I think your main issue is that you're modifying an array while your looping. Obviously with my fix you'll get an out of bounds error on the second splice.

var check = $.inArray(sParentValue, dTrackerArray);
      if (check != -1) {
       for(var i = dTrackerArray.length; i >= 0; i--) {
         if( dTrackerArray[i] === sParentValue ) {
          dTrackerArray.splice(i,1);
          dTrackerArray.splice(i-1,1); //when i == 0 then exception
          }

      }}

Since you know the format of the array you can do this with a while loop:

var check = $.inArray(sParentValue, dTrackerArray);
while(check > -1)
{
  dTrackerArray.splice(check,1);
  check = $.inArray(sParentValue, dTrackerArray); 
}

Upvotes: 1

Piotr Stapp
Piotr Stapp

Reputation: 19830

The problem is in for loop. you start from: var i = dTrackerArray.length and take dTrackerArray[i] this element does not exist. More over you forgot to interate with 0 index element. So you have to change your for loop to:

for(var i = dTrackerArray.length-1; i >= 0; i--)

Upvotes: 4

Jordan Wilcken
Jordan Wilcken

Reputation: 316

You've already stepped through this with a debugger? That's probably all you'd need to do to understand what's happening here. I'd put this in a comment, but I don't have those privileges yet.

Upvotes: 0

Related Questions