Help with Basic Algorithm Scripting: Falsy Bouncer

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

[ false, null, 0, NaN, undefined, '' ]
This value contains all falsy values. Your function doesn’t have a method to handle that.

Thanks for the response!

I realized my problem was that, in the splice method, I was removing i number of elements when I need to remove exactly 1 element every time. I changed it to arr.splice(i, 1), and it now works.

1 Like