15

Why 0 is not returned by the following filter ?

[0, 5, 4].sort().filter(function(i){return i}) // returns : [4, 5]
1
  • 2
    What exactly were you hoping to filter? Commented Apr 15, 2014 at 16:30

5 Answers 5

16

0 is considered a falsy value.

Your filter function is essentially returning false for 0 and filtering it from the array.

Check this out for a deeper look.

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

Comments

13

.filter() function by default excludes falsy items from filtered output.

// ----- falsy items in JS --------
false 
null 
undefined
0 
NaN
'' //Empty string

Solution :

If you still want to keep them, just remember this short tip :


Return true to keep the element, false otherwise.

Example :

[0, 5, 4].sort().filter(function(i){
return true // returning true to keep i element
});

Comments

8

filter is to check for a condition. You are returning the value itself, which is not a correct usage. For this it should be

[0, 5, 4].sort().filter(function(i){return true;}); //[0,4,5] is returned

when you pass values itself, all non-zeros numbers equal to truthy and 0 equals falsy value and so it is ignored by filter. If you still want to stick to this way, due to some reason, enclose 0 within quotes and that will solve the problem.

[0, 5, 4].sort().filter(function(i){return i==0?'0':i;}) //[0,4,5] is returned

Comments

7

To keep 0, but still filter out falsy values, try this:

[0, 5, undefined, 4, null, 7, NaN, -4].sort().filter(function(item){
  return item || item === 0;
});

Edit: Refactored with ES2015 arrow function

[0, 5, undefined, 4, null, 7, NaN, -4].sort().filter(item => item || item === 0);

Comments

1

Try this:

[0, 5, 4].sort().filter(function(i){
    return ((i) ? i : !i);
})

1 Comment

isn't this equal to return true :P

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.