How to Loop Through Array and Remove Items Without Breaking the For Loop
Read this JavaScript tutorial and learn some useful information about the method of looping through an Array and removing items without breaking 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 <kbd class="highlighted">splice()</kbd> method is used to remove an element; however, the array is being re-indexed when you run <kbd class="highlighted">splice()</kbd>, 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 <kbd class="highlighted">splice()</kbd> 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"] */Let's see this in action. If we run the following snippet, we'll notice that 3 is still in the array:
Now, let's fix this problem together. We can either decrement <kbd class="highlighted">i</kbd> after a <kbd class="highlighted">splice()</kbd> or iterate in reverse.
Note: This approach works but is O(n²) for large arrays because indexOf scans the array repeatedly. For better performance, consider the filter method shown later.
When iterating backwards, removing an element only shifts the indices of items we've already processed. The next item to check (at i - 1) remains unaffected, preventing the index-skipping issue.
Or we can start looping in reverse:
Let's get it done more elegantly!
We can also use the JavaScript <span class="attribute">filter</span> method, which takes a callback function as a parameter. We declare our condition, and it returns our desired array.
This way, it's much cleaner!