While vs forEach used with splice
Using forEach() can have unforeseen side effects as we mutate the array in the middle of the loop, causing the index to update. It's generally simpler to use use a general while() loop.
by leviputna
JavaScript
let arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
let i = 0;
while (i < arr.length) {
if (arr[i] === 5) {
arr.splice(i, 1);
} else {
++i;
}
}
console.log("Corect", arr); // arr = [1, 2, 3, 4, 1, 2, 3, 4]
arr = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
arr.forEach(el => {
if (el === 4) {
arr.splice(el, 1);
}
});
console.log("Wrong", arr); // arr = 1, 2, 3, 4, 2, 3, 4, 5]