Skip to content
the poor coder

javascript remove element from array in foreach

Poor Man
Published
Reading time
1 min read

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC