Falsy-bouncer (basic algoritham)

Falsy-bouncer (basic algoritham)
0.0 0

#1

Hi!
why would this code not work i dont know it works on console editor also on other ways i have tried but not on

function bouncer(arr) {
 for(var i = 0; i < arr.length; i++){
   
   if(arr[i] == false || arr[i] == null || arr[i] === 0 || arr[i] == "" || arr[i] == undefined || arr[i].isNaN ) {
     arr.splice(i, 1);
     
   }
   
 } 
  
  return arr;
}

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

#2

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

I don’t want to read code, it’s 2:11 am in the morning… but I can tell you this:

arr[i].isNaN

Should be:

isNaN(arr[i])

#4

A couple of issues:

  • To test for NaN, use either of the following:
    Number.isNaN(myVar); // clearest and most idiomatic
    myVar !== myVar; // NaN is the only value in JS that doesn't equal itself
    
    Don’t use either of these:
    myVar.isNaN;  // will always evaluate to `undefined` unless myVar has a
    // property called `isNaN`
    isNaN(myVar); // evaluates to `true` for `NaN`, but also for any value that
    // isn't a number (strings, objects, etc.)
    
  • When you splice the array, the array gets shorter but the value of i stays the same, so you end up skipping over one element each time you splice. To fix this, you can either decrement i within the conditional (this is risky and can lead to infinite loops if you’re not careful), or use the filter() method instead.

Note that your conditional doesn’t need to be that long. You’re testing for falsiness, which is an intrinsic feature in JavaScript. A quick way to check if a value is falsy is to use !val.


#5

Hi! Thanks man it makes a lot of sense. I forgot i had to decrement the value of i and change isNan to Number.isNaN(arr[i])

It wont result in infinite loop as the condition included arr.length which will reduce everytime the array is splice