Falsy Bouncer I want to understand the mistake

Tell us what’s happening:

Your code so far


function bouncer(arr) {

  for(var key in arr){
    if(Boolean(arr[key] == false))
      arr.splice(key,1);
  }

  console.log(arr);
  return arr;
}

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

Your browser information:

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

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

I can’t what understand wham I am doing wrong. Make me understand please.

You are just looping through an array and changing this array from splice method. Note that the original array is changed by the splice method.

1 Like

I think you can remove the Boolean keyword from your for loop, arr[key] == false should be ok without it.
My first attempt also involved the splice method like your solution, but I was never able to get the correct answer.
I approached the problem by checking for which elements were equal to true and pushing them to a new array.

function bouncer(arr) {
  // A new empty that will hold true values
  let arr2 = [];
  // If arr[i] is true, add it to arr2
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) {
      arr2.push(arr[i]);
    }
  }
  return arr2;
}
bouncer([7, "ate", "", false, 9]);

You do need to remove the Boolean keyword, the result of that will always be true as the result of a comparison will always be a Boolean.

Additionally, since the splice method will modify the array you are iterating through, you are changing the array you are trying to evaluate. When you the 3rd element is evaluated as false and removed, your array becomes [7,“ate”, false, 9]. On the next iteration you mean to evaluate the new 3rd element (false) but the variable “key” has incremented to 4 and you are evaluating the new 4th element “9”. So the element with “false” is never removed. This is why it is important to create a new array for to return rather then try to iterate through the same array as you are changing.