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!)