Looping through array and removing items, without breaking for loop Looping through array and removing items, without breaking for loop javascript javascript

Looping through array and removing items, without breaking for loop


The array is being re-indexed when you do a .splice(), which means you'll skip over an index when one is removed, and your cached .length is obsolete.

To fix it, you'd either need to decrement i after a .splice(), or simply iterate in reverse...

var i = Auction.auctions.lengthwhile (i--) {    ...    if (...) {         Auction.auctions.splice(i, 1);    } }

This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.


This is a pretty common issue. The solution is to loop backwards:

for (var i = Auction.auctions.length - 1; i >= 0; i--) {    Auction.auctions[i].seconds--;    if (Auction.auctions[i].seconds < 0) {         Auction.auctions.splice(i, 1);    }}

It doesn't matter if you're popping them off of the end because the indices will be preserved as you go backwards.


Recalculate the length each time through the loop instead of just at the outset, e.g.:

for (i = 0; i < Auction.auctions.length; i++) {      auction = Auction.auctions[i];      Auction.auctions[i]['seconds'] --;      if (auction.seconds < 0) {           Auction.auctions.splice(i, 1);          i--; //decrement      }}

That way you won't exceed the bounds.

EDIT: added a decrement in the if statement.