4

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?

2
  • 2
    Add && !isNaN(value) to the end of your filter? Commented Sep 30, 2020 at 13:29
  • 1
    Just add an if ( ... ) for when value is falsy to test for "" and 0 Commented Sep 30, 2020 at 13:29

4 Answers 4

6

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

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

Comments

6

Try:

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

Comments

2

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

Comments

1

const values =["",0,"one",NaN,1,"two",2,null,"three",undefined,3,false]
let filterValue = values.filter((e) => {
  if (e === "" || e === 0) {
    return Boolean(!e)
  }
  return Boolean(e)
});

console.log(filterValue)

Comments

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.