How to Delete an Element in a JavaScript Foreach Loop?

Estimated read time 1 min read

In JavaScript, you cannot delete an element from an array directly while iterating over it using the forEach() method. The reason for this is that the forEach() method does not provide an index that you can use to remove the element from the array.

However, there are a few workarounds that you can use to achieve the same effect:

  1. Use a regular for loop: You can use a regular for loop to iterate over the array, and remove the element using the splice() method. Here’s an example:
let arr = [1, 2, 3, 4, 5];

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

console.log(arr); // Output: [1, 2, 4, 5]
  1. Use the filter() method: You can use the filter() method to create a new array that excludes the element you want to remove. Here’s an example:
let arr = [1, 2, 3, 4, 5];

arr = arr.filter((item) => item !== 3);

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

Both of these methods will allow you to remove an element from an array while iterating over it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply