0

I'm attempting to loop through an array and remove any values that equal false, null, 0, undefined, NaN, or "".

When I call the function it should return a blank array but right now it's outputting [null,0,null,null,""]. Here's what I have so far.

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

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

Can anyone tell me what I'm doing wrong and why it is not removing these values from the array?

7
  • 1
    You're if condition is wrong, that is not how you check a variable against multiple values. Also you shouldn't iterate over an array while modifying it without taking proper steps (eg iterating backwards) Commented Jan 22, 2018 at 3:05
  • 3
    Have you considered using Array.prototype.filter instead? Commented Jan 22, 2018 at 3:07
  • Also, once you remove one element, all the others are shifted. So if you remove arr[0], the for loop will continue next time with arr[1], but as the array was shifted, that arr[1] is what used to be at arr[2]. So you'll be skipping elements (try in the reverse order to avoid this). Commented Jan 22, 2018 at 3:07
  • Also, do you know that if(!arr[i]) { will get most of the work done for you? Commented Jan 22, 2018 at 3:08
  • @PatrickEvans Could you be a little more specific about what exactly is wrong about my if condition? Commented Jan 22, 2018 at 3:14

3 Answers 3

2

The problem is with this line:

if(arr[i]===false||null||0||undefined||NaN||""){...}

The correct way to compare for multiple values is:

if(arr[i]===false|| arr[i]=== null|| arr[i]===  0||arr[i] ===  undefined|| arr[i] ===  NaN|| arr[i]===  ""){ ..}

You can simplify it further as all values we need to filter naturally evaluates to false

if(!arr[i])

Reimplementation of your function with the index adjusted for splicing:

function bouncer(arr){
    for( var i = 0 ; i < arr.length ; i++ ){
        if(!arr[i]){
            arr.splice(i--,1);
        }
    }
    return arr;
}

A better way to do this with immutability is by using Array.filter

function bouncer(arr){
    return arr.filter((item) => (!!item));
}
Sign up to request clarification or add additional context in comments.

2 Comments

@RaphaMex I tried experimenting in my browser console with a few logs.. Looked okay to me.. can you show me a case where that might happen?
Sorry you're right, .length is re-evaluated at each loop. Nothing to edit.
0

You might want to read the javascript language syntax descriptions, again.

if(arr[i]===false||null||0||undefined||NaN||"") ...

means, if arr[i] is false, or null is true or 0 is true or undefined is true or NaN is true or "" is true. The first part depends on what arr[i] is, but the rest will all be false. That means we can simplify your statement, as written, to:

if (arr[i] === false) ...

Since the all the rest will always be false. But inferring what you want to do, you might want to say

if (arr[i] == false) ...

which will perform a looser, less rigorous comparison (i.e., it won't check the types of the elements being compared) and will test what I infer you want.

However, your logic has another problem: you are removing elements as you're iterating over the array, i is advancing as you are removing elements from under it. Another approach might be to build up the returned array (rather than modify the input array).

function bouncer(arr) {
  var r=[];
  for(i=0;i<arr.length;i++){
    if ( arr[i] )
      r.push(arr[i]);
  }
  return r;
}

Or better yet, use a method which is designed for the purpose of determining elements to keep (though it does not modify the original array, so you'll have to reassign it:

arr = arr.filter(function (elem) { return elem; });

Comments

0

mistakes:

  1. Should be if(arr[i]===false||arr[i]===null||arr[i]===0||arr[i]===undefined||arr[i]===NaN||arr[i]==="")
  2. Since NaN !== NaN, should use isNaN(arr[i])
  3. if (...) { arr.splice(i,1); i--; // should minus one here! }

2 Comments

2. Should the condition then be arr[i]===isNaN(nan) ?
@PaulPearce isNaN(arr[i])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.