I am trying to remove an element in an array in a forEach
loop, but am having trouble with the standard solutions I\'ve seen.
This is what I\'m current
Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.
You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for
(à la C language):
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === 'a') {
arr.splice(i, 1);
}
}
document.body.append(arr.join());
If you really think about it, a forEach
is just syntactic sugar for a for
loop... So if it's not helping you, just please stop breaking your head against it.