Filter null from an array in javascript

I have a task to remove false, null, 0, "", undefined and NaN elements from the given array. I worked on a solution that removes everything except null. Can anyone explain why? Here is 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]);
+4
source share
4 answers

Well, since all your values ​​are false, just do a !!cast to boolean:

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

Edit: Obviously the actor is not needed:

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

And the above code removes nulljust fine NaN, that is the problem. NaN !== NaNas Nina says in her answer.

+11
source

This is a problem with NaN, because

NaN !== NaN

: NaN.

.

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

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

You can use Array.prototype.filterto verify credibility - see demo below:

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

console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));
Run codeHide result
+1
source

Using

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

console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));
Run codeHide result
0
source

Source: https://habr.com/ru/post/1665006/


All Articles