Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0 not removed from the list?

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]
like image 331
user1766760 Avatar asked Jul 09 '13 17:07

user1766760


3 Answers

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; });
like image 167
Andy Jones Avatar answered Oct 08 '22 12:10

Andy Jones


Every time you remove a value from the array, you skip the one that follows it, because the array is reindexed on every splice. You can loop backwards instead:

var array = [2, 5, 9, 14, 0, 1, 3, 6, 7];
for (var i = array.length-1; i >= 0; i--) { 
    if (array[i]%2 == 0) { 
        array.splice(i,1); 
    } 
}
like image 40
bfavaretto Avatar answered Oct 08 '22 11:10

bfavaretto


It skips the 0 because splice re-indexes the array. use this:

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); 
        i = i - 1;
    } 
}
like image 22
Gyandeep Avatar answered Oct 08 '22 11:10

Gyandeep