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:
- Use a regular
for
loop: You can use a regularfor
loop to iterate over the array, and remove the element using thesplice()
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]
- Use the
filter()
method: You can use thefilter()
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.
+ There are no comments
Add yours