0

I am trying to write a Javascript code that removes all the false values from a given array. The code works for the first negative value is finds and doesn't work on subsequent false values as if once the switch is run, the whole for loop is broken.

My code is below.

  function bouncer(arr) {
  for(var i=0;i<arr.length; i++){

    switch(arr[i]){
      case false:
      case null:
      case 0:
      case "":
      case undefined:
      case NaN: arr.splice(i,1); break;
    }
  }

  return arr;
}

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

Is this normal switch behaviour?

2 Answers 2

5

splice mutates the array, which is not a good thing to do while you're iterating over the array; if the item at i is detected as falsey and is spliced out, once that for loop iteration ends, i will be incremented by one. So, for example, if i started at 2, the item at 2 is deleted, then the item that was at 3 is now at 2. But the new item at 2 is never checked, because i has been incremented to 3.

Use .filter instead, which evaluates every item in the array, and does not have indexing problems nor does it require manual iteration:

const bouncer = (arr) => arr.filter((item) => {
  switch (item) {
    case false:
    case null:
    case 0:
    case "":
    case undefined:
    case NaN:
      return false;
  }
  return true;
});

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

Or, of course, you could just check whether each item is falsey or not:

const bouncer = (arr) => arr.filter(Boolean);

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You for such excellent details. Would accept the answer asap.
1

Yes, part o the issue is, in fact, the splice function mutating the array.

Let me add some more aspects. The case NaN won't ever work as you are expecting it to, because NaN != NaN. So to tell if a certain value is NaN use isNaN(var).

Sugestion: A simple shortcut for what you're trying to achieve would be const bouncer = (arr) => arr.filter(Boolean);. This will effectively remove false values, including NaN ones. You can test the values one-by-one by calling in a js console for eg.: Boolean(""), Boolean(0) and so on.

2 Comments

Thank you. You're right about the Nan value. Could you tell me where should I learn the working of higher-order functions like filter and map?
For the specification of all available methods present in the Array.prototype go here. If you want to have a peek at some shims implementations take a look here, if this answers your question.

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.