Removing all falsy values from a javascript array, including NaN but excluding 0 and empty strings

918 views Asked by At

I have the following array:

const values = ['', 0, 'one', NaN, 1, 'two', 2, null, 'three', undefined, 3, false];

I would like to filter() out all the falsy values except for '' and 0.

I understand there is useful shorthand:

return values.filter(Boolean)

but this removes all the falsy values including '' and 0.

I have tried the following, instead:

return values.filter(value => [NaN, null, undefined, false].indexOf(value) < 0);

and it's almost right... but it does not remove NaN.

const values = ['', 0, 'one', NaN, 1, 'two', 2, null, 'three', undefined, 3, false];

const filteredValues = values.filter(value => [NaN, null, undefined, false].indexOf(value) < 0);

console.log(filteredValues);

Is there any way to achieve the same result as this last example, but also remove NaN?

3

There are 3 answers

0
str On BEST ANSWER

NaN is not equal to itself (i.e. NaN === NaN evaluates to false), thus using it with indexOf fails. Another approach that also conveys your goal ("filter() out all the falsy values except for '' and 0") better is the following:

const values = ['', 0, 'one', NaN, 1, 'two', 2, null, 'three', undefined, 3, false];
const filteredValues = values.filter(value => value || value === '' || value === 0);
console.log(filteredValues);

0
Mitya On

Try:

values.filter(value => value || value === '' || value === 0);
0
Sash Sinha On

You can also consider using a Set since you can check if a set contains NaN and the time complexity for has is O(1), rather than O(n), where n is the number of items you need to check:

const values = ['', 0, 'one', NaN, 1, 'two', 2, null, 'three', undefined, 3, false];
const notAllowed = new Set([NaN, null, undefined, false]);
const result = values.filter(val => !notAllowed.has(val));
console.log(result);