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

        }
    });        
1

3 Answers 3

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.

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

2 Comments

Just a heads-up: I think this doesn't work in IE < 9.
@SimonSteinberger The link has a polyfill for browsers that don't support .filter() natively.
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);
    }
});

Comments

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
};

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.