Removing falsy values from an Array

Hello,

So I am trying to solve the “Basic Algorithm Scripting: Falsy Bouncer” challenge where I most remove falsy values from an array, but my code isn’t working!

can you please take a look and tell me what is going wrong here?

I also put a console.log statement inside the if statement but it’s not being called at all.

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

bouncer([7, "ate", "", false, 9]);

Hey it look like you have a typo in the for loop. arr.lenrth should be arr.length

First issue is this

Then you are changing the array while looping over it. If you add console.log(i, arr[i]) before the if statement you will see it doesn’t follow the sequence of the items in the array as it should - to solve this you should find a different way (not using splice), or looping on the array in a different way

Instead of using splice, try starting with a new array, then only append items from arr to it if the item is truthy.

Thanks a lot everyone, now I know that I should not change an array’s length (sorry about the typo earlier) while iterating through it, so I made a new array and pushed only the truthy values to it.

Now my code look like this:

Spoiler:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  let targetArr = [];
  for (let i = 0; i < arr.length; i++){
    if (arr[i]) {
      targetArr.push(arr[i]);
    }
  }
  return targetArr;
}

bouncer([7, "ate", "", false, 9]);

I was actually just having a discussion in a thread about this same problem. While not something you would notice an issue with from the example input array, you should modify your if condition for best practices since while 0 and “” will automatically undergo type coercion and equate to false, NaN, null, and undefined will not. So you would want to do something like if (Boolean(arr[i]))

I did the same thing!

if(!arr[i]) actually works, it’s just comparison to false that doesn’t, i.e. if(arr[i] == false) doesn’t do quite what you expect

1 Like

Ah right, since there is no automatic type coercion for those values for example:

NaN == true returns false
but also
NaN == false returns false

so the condition still accomplishes it’s goal in this case. Definitely an important behavior thing to notice though, I didn’t until you pointed it out to me in my thread.

1 Like