1

I have a loop that goes through an array and removes some elements from it.

But since it removes the elements from the same array it's looping on, it creates some problems.

Here I have Players from which I wanna remove a player2

Players = [];
Players.push('player1');
Players.push('player2');
Players.push('player2');
Players.push('player2');
Players.push('player3');
Players.push('player2');
Players.push('player2');
Players.push('player2');

function check() {
    for (var i = 0; i < Players.length; i++) {
        if (Players[i] == 'player2')
            kick(Players[i])
    };
}

function kick(player) {
    for (var i = 0; i < Players.length; i++) {
        if (player == Players[i]) {
            Players.splice(i, 1);
            break;
        }
    };
}

but

check();

console.info(util.inspect(Players));

outputs

[ 'player1', 'player3', 'player2', 'player2' ]

What could I do to correct this?

Community
  • 1
  • 1
laggingreflex
  • 26,275
  • 28
  • 123
  • 172

2 Answers2

6

mind blowing trick: run through the array backwards.

You're hitting the "concurrent modification" scenario (splicing out an element at position i changes the position for all elements after it), so avoid that with:

for(i=arr.length-1; i >=0; i--) {
  // ...
  if (shouldberemoved) {
    arr.splice(i,1);
  }
}

now you can remove as many elements as you like without affecting the elements preceding it.

Mike 'Pomax' Kamermans
  • 40,046
  • 14
  • 84
  • 126
2

Why don't you run the loop in reverse order.

for (var i = Player.lenght; i < 0; i--)

then if you remove, you will not be looking for those elements.

Anthony Horne
  • 2,324
  • 2
  • 26
  • 49