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]
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; });
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);
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With