Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through array and removing items, without breaking for loop

I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined. I could check if it's undefined, but I feel there's probably a more elegant way to do this. The desire is to simply delete an item and keep on going.

for (i = 0, len = Auction.auctions.length; i < len; i++) {     auction = Auction.auctions[i];     Auction.auctions[i]['seconds'] --;     if (auction.seconds < 0) {          Auction.auctions.splice(i, 1);     }            } 
like image 505
dzm Avatar asked Mar 27 '12 01:03

dzm


1 Answers

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.length while (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.

like image 101
4 revs, 3 users 76%user1106925 Avatar answered Oct 22 '22 00:10

4 revs, 3 users 76%user1106925