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?

4
  • 1
    Why don't you just remove them? if (Players[i] == 'player2') { delete Players[i]; } Commented Apr 7, 2014 at 20:46
  • 1
    see answer to: stackoverflow.com/questions/9882284/… Commented Apr 7, 2014 at 20:48
  • @feeela It makes my array sparse. >[ 'player1', , , , 'player3', , , ] Commented Apr 7, 2014 at 20:54
  • 1
    It's redundant to search for the entry twice. After the first search, you know exactly where the thing is. Commented Apr 7, 2014 at 20:58

2 Answers 2

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.

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

Comments

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.

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.