Phaser.js delete object in group during forEach loop
<p>I want to destroy an object after it passes a certain x value.
The objects are part of a phaser group called balls.
In my update loop, I have this line of code:</p>

<pre><code>balls.forEach(updateBalls, null, true);
</code></pre>

<p>Here is the updateBalls function:</p>

<pre><code>function updateBalls(ball) {
  if (ball.x &gt; 800) {
    ball.destroy();
  }
}
</code></pre>

<p>The problem is that deleting the object during the loop messes up the loop, this is the error I get:</p>

<blockquote>
  <p>TypeError: this.children[i] is undefined</p>
</blockquote>

<p>I tried to push each of the balls to an array and then destroying each ball like this.</p>

<pre><code>function updateBalls(ball) {
  if (ball.x &gt; 800) {
    ballsToDestroy.push(ball);
  }
}
</code></pre>

<p>Then in the update loop:</p>

<pre><code>balls.forEach(updateBalls, null, true);
for (x = 0; x &lt; ballsToDestroy.length; balls++) {
    ballsToDestroy[x].destroy();
}
</code></pre>

<p>This gave me some odd bugs though.<br>
It works if I use ball.kill(), but that will eventually make the game lag because the balls aren't actually removed.</p>

<p>How can I get around this?</p>