javascript remove element from array in foreach

Removing elements from an array during a forEach() loop can be a tricky process. This is because forEach() loops through the array in order and thus when you remove an element from the array, you are essentially changing the size of the array and thus the index of the elements that follow the one you removed.

The best way to go about this is to use a for loop instead of forEach(). The for loop allows you to iterate through the array backwards, starting at the last index and working your way to the first index. This way, when you remove an element, the index of the elements after it are unaffected.


let arr = [1, 2, 3, 4, 5];

for (let i = arr.length - 1; i >= 0; i--) {
  if (arr[i] === 3) {
    arr.splice(i, 1);
  }
}

console.log(arr); // [1, 2, 4, 5]

In the example above, we create an array with 5 elements and then loop through it using a for loop, starting at the last index and working our way to the first. If the current element is equal to 3, we remove it using the splice() method. After the loop is finished, we have a new array without the element 3.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe