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. To fix it, you can either decrement i after a splice() or simply iterate in reverse:

let elements = [1, 3, 3, 5, 3, 1, 4];
for (let i = 0; i < elements.length; i++) {
  if (elements[i] == 3) {
    elements.splice(i, 1);
  }
}
console.log(elements);
let elements = [1, 3, 3, 5, 3, 1, 4];
let removeEl = 3;
let index = elements.indexOf(removeEl);
while (index !== -1) {
  elements.splice(index, 1);
  index = elements.indexOf(removeEl);
}
console.log(elements);
let elements = [1, 3, 8, 5, 16, 1, 4];
for (i = elements.length - 1; i >= 0; --i) {
  if (elements[i] % 2 === 0) {
    elements.splice(i, 1); // Remove even numbers
  }
}
console.log(elements);

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, and in the iteration, the next item is lower than the current point.

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.

Do you find this helpful?

Related articles