javascriptarraysfilternan

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


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?


Solution

  • 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);