Array.sort().filter(...) with zero in Javascript

Why 0 is not returned by the following filter ?

[0, 5, 4].sort().filter(function(i){return i}) // returns : [4, 5]

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.


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

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

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

Try this:

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