Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through array when removing elements

I'm wondering if and what is a reliable and/or standard way of iterating an array whose length is changing inside the loop. I ask because I end up choosing a different method to do this each time I want to do it, e.g.

for ( var i = 0; i < myarray.length; i++ ) {
  if (myarray[i] === 'something') {
    myarray.splice(i, 1);

    // *to avoid jumping over an element whose index was just shifted back to the current i
    i--;
  }
}

or

var i = 0;
while (myarray[i]) {
  if (myarray[i] === 'something') {
    myarray.splice(i, 1);
  } else {
    i++;
  }
}

These are the ways I find myself doing this, but I'm curious if there is a standard approach.

like image 895
rob-gordon Avatar asked Jun 26 '13 12:06

rob-gordon


1 Answers

I find simpler to iterate in the other direction :

for (var i=myarray.length; i--; ) {
   if (myarray[i] === 'something') myarray.splice(i, 1);
}

This way you don't have to change the increment when removing.

Many developers, especially the ones who didn't deal with C-like languages before JavaScript, find it confusing to deal with the subtleties of the decrement operator. The loop I wrote can also be written as

for (var i=myarray.length-1; i>=0; i--) {
like image 137
Denys Séguret Avatar answered Oct 03 '22 23:10

Denys Séguret