Why is 0 not removed from the list?

arrays, javascript, modulo

Solution

0 is getting skipped

You are mutating (changing) the array while you're iterating through it. This is a programming no-go.

Let's walk through...

i = 0 and 2 is even and gets spliced, your array is now [5, 9, 14, 0, 1, 3, 6, 7]

i = 1 and we didn't even check 5 which is in index 0 now... we're now checking 9 which is odd, fine

i = 2 and 14 is even and gets spliced, your array is now [5, 9, 0, 1, 3, 6, 7]

i = 3 and 0 gets skipped (as 0 is in index 2 now), 1 is odd, fine

i = 4 is odd fine

i = 5 is even and get spliced

i = 6 is odd fine

What you really want is this...

Array.prototype.filter = function(func) {
  var result = new Array();
  for (var i = 0; i < this.length; ++i) 
    if (func(this[i]))
      result.push(this[i]);
  return result;
}

values = [2, 5, 9, 14, 0, 1, 3, 6, 7];
odd_only = values.filter(function(x) { x % 2 != 0; });

Problem

I was testing out how `splice` works while iterating through an array, and don't understand why 0 stayed in the list? ``` var array = [2, 5, 9, 14, 0, 1, 3, 6, 7]; for (var i = 0; i < array.length; i++) { if (array[i]%2 == 0) { array.splice(i,1); } } //0 % 2 == 0 is true, and yet //array = [5, 9, 0, 1, 3, 7] ```

Original source