Falsy Bouncer algorithm help

I have been trying for two days to figure out the Falsy Bouncer algorithm, and I cannot seem to understand what I’m doing wrong here.

Here’s the pseudocode explanation for the algorithm I’ve tried to implement:

``````Check each item in the input array
if item is the same as false or item converted to boolean is false
splice that item out of the array
return the array
``````

And here is my code:

``````function bouncer(arr) {
console.log(arr);
for (let i = 0; i < arr.length; i++) {
console.log(arr[i], Boolean(arr[i]), arr[i] == false);
if ( Boolean(arr[i]) == false || arr[i] == false) {
arr.splice(i,1);
}
}
console.log(arr);
console.log("------");
return arr;
}
``````

Something about this solution is not working. Here is some example console output (printing the array before the for loop, then `i` and the result of each of the two tests, then the final `arr` just before it is returned)

``````7 true false
ate true false
false true                <-- false should come next, but never prints
9 true false
[7, "ate", false, 9]        <- false retained?
------
["a", "b", "c"]
a true false
b true false
c true false
["a", "b", "c"]
------
[false, null, 0, NaN, undefined, ""]
false false true          <- null should come next but never prints
0 false true              <- NaN should come next but never prints
undefined false false
[null, NaN, ""]           <- null and NaN retained?
------
[1, null, NaN, 2, undefined]
1 true false
null false false           <- NaN should come next but never prints?
2 true false
undefined false false
[1, NaN, 2]                <- NaN retained
``````

Can anyone explain to me why my code is not working? The behavior I’m getting from the console log is throwing me off and I am seriously at a loss trying to understand what’s going on here!

(I have looked up the solution to this exercise already, just want to understand what I was doing wrong!)

Inside your for loop, when i = 2, arr[2] = ‘’. Your if statement evaluates to true, so the ‘’’ value is remove from arr. Now arr only has 4 elements [7, ‘ate’, false, 9].

In the next iteration i =3, and arr[3] = 9, so your if statement evaluates to false and the final array is [7, ‘ate’, false, 9].

The false never gets checked with the if statement, because when you spliced out the ‘’, you still incremented i via the for loop.

Lesson: if you are removing items from an array as you loop through it, the removal will throw off the indexing.

Thank you! That totally makes sense, and also explains why I was seeing multiple values skipped over in the longer arrays deeper in the tests.