$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · medium · #27

Which fix removes the bug?

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