Which fix removes the bug?
const nums = [1, 2, 3, 4];
nums.forEach((n, i) => {
if (n % 2 === 0) nums.splice(i, 1);
});
- Change
splicetoslicein the loop - Filter instead:
nums.filter(n => n % 2 !== 0) - Change
forEachtomapin the loop - Use
i + 1as the splice start index
Mutating an array while iterating skips elements; use filter.
Play Problem Solving ▸