admin管理员组

文章数量:1387391

I tried using isNaN(value) and !isNaN(value) but I am unable to remove the NaN element in the give code without removing the strings. (Obviously because string is not a number).

function cleaner(arr) {
  return = arr.filter(function f(value) {return (value !== false && value !== null && value !== 0 && value !== undefined)});
}
cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]);

The above code should return [7, "eight", 9, ""];

I tried using isNaN(value) and !isNaN(value) but I am unable to remove the NaN element in the give code without removing the strings. (Obviously because string is not a number).

function cleaner(arr) {
  return = arr.filter(function f(value) {return (value !== false && value !== null && value !== 0 && value !== undefined)});
}
cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]);

The above code should return [7, "eight", 9, ""];

Share Improve this question asked Jan 28, 2016 at 3:15 salmanxksalmanxk 3156 silver badges19 bronze badges 8
  • P.s, I think I could have worded the title better but I'm not sure how. – salmanxk Commented Jan 28, 2016 at 3:16
  • false and null and undefined are not NaNs. Only NaN is NaN – zerkms Commented Jan 28, 2016 at 3:16
  • 1 Regardless, the last line of my post will explain what I actually want, to quell any confusion. – salmanxk Commented Jan 28, 2016 at 3:19
  • 4 Guys, seriously, the question has nothing to do with NaNs. – zerkms Commented Jan 28, 2016 at 3:19
  • 2 Just check if typeof of the value is either a string or a number and you're done. – zerkms Commented Jan 28, 2016 at 3:21
 |  Show 3 more ments

3 Answers 3

Reset to default 5

This will return only numbers (without 0) and strings (including empty ones).

function cleaner(arr) {
   return arr.filter(function(item){ 
      return typeof item == "string" || (typeof item == "number" && item);
              /** Any string**/        /** Numbers without NaN & 0 **/
   });
}
console.log(cleaner([7, "eight", false, null, 0, undefined, NaN, 9, ""]));
//[7, "eight", 9, ""]

Using ES2015 Arrow Function syntax

array.filter(item => typeof item == "string" || (typeof item == "number" && item));

var filteredArr = [7, "eight", false, null, 0, undefined, NaN, 9, ""].filter(item => typeof item == "string" || (typeof item == "number" && !isNaN(item) && item));

console.log(filteredArr);

Some ways to detect whether x is NaN:

  • Number.isNaN(x) (ES6)
  • Object.is(x, NaN) (ES6)
  • x !== x
  • (typeof x === 'number') && isNaN(x)

Note: isNaN alone is not a reliable way to check if a value is NaN!

Since you want to filter out all falsy values except empty strings, all you need is

function cleaner(arr) {
  return arr.filter(function(value) {
    return value === '' || value;
  });
}

If you had wanted to filter out all falsy values including empty strings, you could have done:

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

本文标签: