Filter null from an array in JavaScript

JavascriptArrays

Javascript Problem Overview


I have a task to remove false, null, 0, "", undefined, and NaN elements from an given array. I worked on a solution which removes all except null. Anyone can explain why? Here's the code:

function bouncer(arr) {
var notAllowed = ["",false,null,0,undefined,NaN];
  for (i = 0; i < arr.length; i++){
      for (j=0; j<notAllowed.length;j++) {
         arr = arr.filter(function(val) {
               return val !== notAllowed[j];
              });
  }
 }
return arr;
}

bouncer([1,"", null, NaN, 2, undefined,4,5,6]);

Javascript Solutions


Solution 1 - Javascript

Well, since all of your values are falsy, just do a !! (cast to boolean) check:

[1,"", null, NaN, 2, undefined,4,5,6].filter(x => !!x); //returns [1, 2, 4, 5, 6]

Edit: Apparently the cast isn't needed:

document.write([1,"", null, NaN, 2, undefined,4,5,6].filter(x => x));

And the code above removes "", null, undefined and NaN just fine.

Solution 2 - Javascript

It is a problem with NaN, because

NaN !== NaN

read more here: Testing against NaN.

For filtering the values, you could check for truthyness.

function bouncer(arr) { return arr.filter(Boolean); }

console.log(bouncer([1, "", null, NaN, 2, undefined, 4, 5, 6]));

Solution 3 - Javascript

You can use Array.prototype.filter for truthy value check - see demo below:

function bouncer(array) {
  return array.filter(function(e) {
    return e;
  });
}

console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

Solution 4 - Javascript

[1, 2, 0, null, "sdf", ""].filter(a=>a)
// filter non null value, remove 0, null and "" (empty quote)

console.log([1, 2, 0, null, "sdf", ""].filter(a=>a))

Solution 5 - Javascript

Use

function bouncer(arr) {
 return arr.filter(function(item){
   return !!item;
 });
}

console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongshainealaView Question on Stackoverflow
Solution 1 - JavascripttymeJVView Answer on Stackoverflow
Solution 2 - JavascriptNina ScholzView Answer on Stackoverflow
Solution 3 - JavascriptkukkuzView Answer on Stackoverflow
Solution 4 - JavascriptkishoreView Answer on Stackoverflow
Solution 5 - JavascriptJyothi Babu ArajaView Answer on Stackoverflow