Falsy Bouncer - null issue

Falsy Bouncer - null issue
0.0 0

#1

Tell us what’s happening:
I came up with a code that works for every option but sometimes leaves a null element in the array. Could someone please look at the code and tell me why this is? (I know it can be done easier but I am more curious why it doesn’t work like this)
Thank you

Your code so far


function bouncer(arr) {
  const arrLength = arr.length;
   for (let i = 0; i <= arr.length; i++) {
   if (Boolean(arr[i]) == false) {
     arr.splice([i], 1);  
     i = 0;
  } 
  

   }
  console.log(arr);
   return arr;
}

bouncer([null, null]);

Your browser information:

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

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


#2

Have you considered array.filter()?


#4

But that is why I put “i = 0” to reset the counter…


#6

It does remove the NaN, I have tried it.


#8

Input: 0 1 2 false 4 NaN
Output: 1 2 4


#9

so the only scenario it fails is if the all the array is falsy values?

if yes, maybe you need to check if this ‘i’ is the last value in the array. If yes, break out of the loop after you splice.


#10

Exactly so, weird, I know


#12

Interestingly enough, this works but only if every value in the array is falsy


#13

sending a msg so as not to spoil the final solution


#14

not sure what you’re trying to do here but this line “for (let i = 0; i <= arr.length; i++) {” will be trying to access an element that is not in your array


#15

As @macmanmatty points out, there will be no value at arr[arr.length] which is what your for loop condition expression currently allows. Remember, arrays are zero-indexed and start at 0 and go up through arr.length - 1.

Also, you would only set i equal to 1, if you removed just the first element with the splice. What if you have 1,00,000 elements in an array which you need to check and then you take out the 999,999th element with splice, setting i = 0, forces the it to look through the entire array of elements that have already been confirmed not to be falsy. Think about another way you could easily decrement i by 1.