Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all falsy values from an array

I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

function bouncer(arr) {  arr = arr.filter(function (n) {      return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });   return arr; }  bouncer([7, "ate", "", false, 9, NaN], ""); 

The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?

like image 249
Vignesh Avatar asked Oct 02 '15 12:10

Vignesh


People also ask

How do you remove all Falsy values from an array?

We use the filter method to remove falsy values from an array. The filter method filters out all the values that return false when passed to a function. When you use filter and pass a Boolean constructor, you can quickly filter out all the falsy values from the array.

How do you remove the Falsy value of an object?

To remove the falsy values from an object, pass the object to the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete each falsy value from the object.

Is [] truthy or Falsy?

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .

Is empty array Falsy?

Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.


2 Answers

You can use Boolean :

var myFilterArray = myArray.filter(Boolean); 
like image 93
LoremIpsum Avatar answered Sep 21 '22 09:09

LoremIpsum


Since you want to get rid of "falsy" values, just let JavaScript do its thing:

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

The double-application of the ! operator will make the filter callback return true when the value is "truthy" and false when it's "falsy".

(Your code is calling isNaN() but not passing it a value; that's why that test didn't work for you. The isNaN() function returns true if its parameter, when coerced to a number, is NaN, and false otherwise.)

edit — note that

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

would work too as LoremIpsum notes in another answer, because the built-in Boolean constructor does pretty much the exact same thing as !!.

like image 45
Pointy Avatar answered Sep 22 '22 09:09

Pointy