Reputation: 129
If you notice the result of the for loop that is starting at index 0 and counting up isn't taking the number 23 out fo the array.
Using JavaScript Loop through evenArray removing all values that aren't even
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = evenArray.length - 1; i >= 0; i--) {
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
};
console.log(evenArray);
//output to this will be 2, 6, 22, 98, 22, 12;
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = 0; i < evenArray.length; i++) {
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
};
console.log(evenArray);
//output is [2, 6, 22, 98, 23, 22, 12];
Upvotes: 4
Views: 90
Reputation: 2051
Just adding one single print into the code:
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = 0; i < evenArray.length; i++) {
console.log("index:"+i+" value:"+evenArray[i])
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
}
The output like this:
index:0 value:1
index:1 value:3
index:2 value:22
index:3 value:98
index:4 value:45
index:5 value:22
index:6 value:12
Compare to the origin array, it's cutting.
The reason is splice
is cutting your array dynamically, so the index is changed after splice, value 23
origin index is 7
, but after the splice it move to before index 6
[1,2,3,6,22,98,45,23,22,12];
Upvotes: 0
Reputation: 46323
Dylan's answer is correct explaining why one works and the other fails.
Regardless, a simple solution that will work is:
var evenArray = [1,2,3,6,22,98,45,23,22,12];
evenArray = evenArray.filter(function(val) { return val % 2 == 0; });
console.log(evenArray);
Upvotes: 3
Reputation: 13922
When you splice
a number out of the array, all of the values after that point in the array get shifted to the left.
In the second approach, at index 6 the value is 45
. You detect it as odd, so you splice. Now the 23, 22, and 12 get shifted over so that 23 is now at index 6. But since you are iterating forward, your i++
moves you up to index 7, effectively skipping the 23, which is why 23 is in the result.
When you iterate backwards, you avoid this problem because all of the numbers being shifted have already been acted on.
Upvotes: 9