1

I need to remove all empty values (null, undefined, '', NaN, false) EXCEPT 0 from an array. eg: [0, false, [], undefined, {}, NaN, 'Kevin'] => [0, [], {}, 'Kevin'];

function removeBlank(array) {
  array = array.filter(function (n) {
    return (n !== undefined && n !== null && n !== false && n !== "" && isNaN()!= NaN); });
  console.log( array );
}

However this still returns a NaN. for example removeBlank([0, NaN, undefined, false, '', null, 'Kevin']); returns [0, NaN, "Kevin"]

How do I improve the isNaN()!= NaN) to remove NaN with out removing strings, ZEROS or other numbers?

0

2 Answers 2

1

isNaN()!= NaN has no meaning, isNaN is a function that takes a parameter and check (return true or false) if it's a valid number or not, you are not passing to it anything.

And even if you use it right, it won't work, because then all values that are not numbers will be filtered out.

I'd suggest using this:

array = array.filter(function (n) {
    return n || n === 0;
});

either n is truthy or it is 0.

Sign up to request clarification or add additional context in comments.

7 Comments

@MaxES logical OR, it means either side is true or truthy. If n !== false !== "" !== 0 !== NaN !== undefined !== null then it's truthy and then n is equivalent to true so the test is ok. If n === 0 then the left side of || will be equivalent to false, but the right side n === 0 will be true, || need only one true side to be true. So either n is truthy or it is equal to 0.
@MaxES Here is more about logical operators.
If it's Infinity or -Infinity it will return true. Usually it is a bad idea to work with infinite numbers, almost no application deals with them.
@arboreal84 I'm not sure what you are talking about?
@arboreal84 both Infinity and -Infinity are truthy as they should be.
|
0

isNaN takes the number as a parameter. Needs to be isNaN(n)

Then, unless you want to work with infinite numbers, like -Infinity and Infinity, I recommend you just validate with:

arr.filter(function (n) {
   return isFinite(n);
});

NaN is not finite so it would be filtered too. NaN also has the property that any comparison will make it return false. This means n == n will return false if n is NaN.

2 Comments

Infinity should be truthy. I guess.
Infinity is not a number that you can operate with other numbers other than for the purposes of comparison. In that sense, Infinity almost always breaks business logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.