How to Loop Through Array and Remove Items Without Breaking the For Loop
In this tutorial, you will find an elegant way of looping through an Array and removing items without breaking the for loop.
The splice() method is used to remove an element; however, the array is being re-indexed when you run splice(), which means that you will skip over an index when one is removed.
But first, let's get a good grasp of how the splice method works.
The splice() Method
The splice() method modifies the contents of an Array by removing or replacing the existing elements or adding new elements in place. While it changes the original array in place, it still returns the list of removed items. If there is no removed Array, it returns an empty one.
const anyFish= ["angel", "drum", "mandarin", "sturgeon"]; /*Remove 1 element at index 2*/ const removed = anyFish.splice(2, 1); /* anyFish is ["angel", "drum", "sturgeon"] */ /* removed is ["mandarin"] */
So now let's start our example and see that problem. If we run the snippet and look at the result, we will see that 3 is still in the array and that's exactly the problem we mentioned above:
Now, let's fix this problem together. We can either decrement i after a splice() or iterate in reverse.
This will prevent the re-index from affecting the next item in the iteration because indexing has an effect only on the items from the current point to the end of an Array. In the iteration, the next item is lower than the current point.
Or we can start looping in reverse:
Let's get it done more elegantly!
This way, it's much cleaner!