3

I have the following code which iterates through a JS array. When I get to a specific element, I want to remove it. I realise that I can use splice, but is there a way that doesn't involve me tracking the index:

    myArray.forEach(function (point) {
        canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
        point.PointY++;
        canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);

        if (point.PointY > canvas.height) {
            // Remove point

        }
    });        
Maurizio In denmark
  • 4,226
  • 2
  • 30
  • 64
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
  • 1
    Other great (better?) solutions than the here given ones: http://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop – Simon Steinberger Aug 04 '14 at 05:52

3 Answers3

1

Modifying the array in-place can be tricky, so perhaps Array.filter() is a better function to use:

myArray = myArray.filter(function (point) {
    canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
    point.PointY++;
    canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);

    if (point.PointY > canvas.height) {
        return false;
    }
    return true;
});     

It returns an array with all elements for which the callback returned true.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Use the 2nd parameter to forEach, index and Array.splice:

myArray.forEach(function (point, index) {
    canvasContext.clearRect(point.PointX - 3, point.PointY - 3, 6, 6);
    point.PointY++;
    canvasContext.fillRect(point.PointX - 3, point.PointY - 3, 6, 6);

    if (point.PointY > canvas.height) {
        myArray.splice(index, 1);
    }
});
Halcyon
  • 57,230
  • 10
  • 89
  • 128
0

There's often an issue with loops that change the length of the array being looped over. They will end up 'skipping' an item.

It's typical when you're going to affect the length of the array to count down instead of up, with a loop like this:

for (var i = Things.length - 1; i >= 0; i--) {
  //your code here
};
Alex Mcp
  • 19,037
  • 12
  • 60
  • 93