Basic Algorithm Scripting: Falsy Bouncer null Issue

Tell us what’s happening:
I am not able to remove —null-- from the array.

Your code so far

function bouncer(arr) {
// Don't show a false ID to this bouncer.
for(let i=0;i<arr.length;i++){
  console.log(arr[i])
  if(!arr[i]){ 
    arr.splice(i,1);
    i=0}
}
console.log(arr)
return arr;
}

bouncer([7, "ate", "", false, 9]);
bouncer([false, null, 0, NaN, undefined, ""])

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Falsy Bouncer

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer

you are setting i to 0, but then the loop raise it to 1 before using it again. the 0 position is not checked again.

recommendation: do not change the array you are looping over

or fix that issue

1 Like
function bouncer(arr) {
// Don't show a false ID to this bouncer.
for(let i=0;i<arr.length;i++){
  console.log(arr[i])
  if(!arr[i]){ 
    arr.splice(i,1);
    i=0}
}
if(arr[0]==null) arr.splice(0,1); //this solved my problem. Somehow the null wasn't being removed so remove explicitly. this will help to solve your problem
console.log(arr)
return arr;
}

bouncer([7, "ate", "", false, 9]);
bouncer([false, null, 0, NaN, undefined, ""])

Thanks but I solved it. Great to have all campers support.

you have passed the tests, but you have not really solved the challenge

if your array is ["", NaN, true, 0, 1] what does your algorithm return? it should return [true, 1]

1 Like

Thanks for your reply I could have used a very simple solution like. But I want to do it with a for loop that’s my challenge. Thanks for pointing out the flaw. I’ll make another one.

function bouncer(arr) {
// Don't show a false ID to this bouncer.
let newArr=arr.filter((x)=>x==true)
console.log(newArr)
return newArr
}

I got you. Very smart to point that out.

Okay then I made i= -1 and then the solution worked. so that i would be 0 after increasing.

good job!
suggestions to make your algorithm more performing:

  • instead of setting i back at the beginning each time you could instead do i-- when you splice to count for the removed element,
  • or you could count backward so you don’t need to change the value of iafter splicing