Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my solution work and this other solution doesnt?

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];

like image 442
Ryan Hamblin Avatar asked Dec 14 '22 13:12

Ryan Hamblin


1 Answers

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.

like image 181
Dylan Avatar answered Jan 10 '23 23:01

Dylan