Hello, all!
I am working on the Falsy Bouncer algorithm challenge, and I can’t figure out why my solution doesn’t work. It actually passed these tests: [7, "ate", "", false, 9]
and ["a", "b", "c"]
, but not the rest. If I pass in [false, null, 0, NaN, undefined, ""]
, I get this message:
Potential infinite loop detected on line 3. Tests may fail if this is not changed.
and this output: [ false, null, 0, NaN, undefined, '' ]
, i.e. no change.
Here is my solution. Can someone please explain what makes the loop infinite and why the falsy elements aren’t being spliced out of the array? Thanks for any assistance you can provide!
function bouncer(arr) {
let i = 0;
while (i < arr.length) { // loop through each element
if (!!arr[i] == false) { // if the element is falsy,
arr.splice(i,i); // then splice it out and start over with the same i position since the falsy element was removed
} else { // else move on to the next element
i++;
}
}
return arr;
}