1

I have the following code:

  $.each(current, function(index, value) {
     thisArray = JSON.parse(value);
     if (thisArray.ttl + thisArray.now > now()) {
        banned.push(thisArray.foodID);
     }
     else{
        current.splice(index,1);
     }
  });

There's a problem with the following line:

current.splice(index,1);

What happens is that it (probably) unsets the first case which fits the else condition and then when it has to happen again, the keys don't match anymore and it cannot unset anything else. It works once, but not in the following iterations.

Is there a fix for this?

2

3 Answers 3

2

You can use a regular for loop, and loop backwards:

for(var i=current.length-1; i>= 0; i--) {
   var thisArray = JSON.parse(current[i]);
   if (thisArray.ttl + thisArray.now > now()) {
      banned.push(thisArray.foodID);
   } else {
      current.splice(i, 1);
   }
});

Also it seems thisArray is actually an object, not an array...

Sign up to request clarification or add additional context in comments.

Comments

0

you can use regular for loop, but after splice, decrease index by 1

for(var i=0; i<current.length; i++){
    current.splice(i, 1); i--;
    }

Comments

0

You should pay attention if you mutate an array (by moving objects) while it's being traversed because some element may get skipped like in your case.

When you call current.splice(index, 1) element index will be removed and element index+1 will take its place. But then index will be incremented, thus skipping one element.

A better solution is IMO the read-write approach. You keep one index as the "read pointer" and you always increment it, and another index (the "write pointer") that is incremented only when you decide an element should be kept in the array:

var wp = 0;  // The "write pointer"
for (var rp=0; rp<a.length; rp++) {
    if (... i want to keep element a[rp] ...) {
        a[wp++] = a[rp];
    }
}
a.splice(wp); // Remove all elements after wp

This is a o(N) operation and will move each element at most once. Other approaches like starting from the end and using the same splice(i, 1) approach instead will keep moving all elements after i each time an element needs to be removed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.