Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter null from an array in JavaScript

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]); 
like image 997
gshaineala Avatar asked Dec 27 '16 14:12

gshaineala


People also ask

How do you remove the null from an object array?

To remove all null values from an object: Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array of keys. Check if each value is equal to null and delete the null values using the delete operator.

How do you filter an array in JavaScript?

JavaScript Array filter() The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

How do you filter an undefined array?

To remove all undefined values from an array: Use the Array. filter() method to iterate over the array. Check if each value is not equal to undefined and return the result. The filter() method will return a new array that doesn't contain any undefined values.

IS null == null in JavaScript?

Summary. null is a special value in JavaScript that represents a missing object. The strict equality operator determines whether a variable is null: variable === null .


1 Answers

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.

like image 136
tymeJV Avatar answered Sep 20 '22 01:09

tymeJV