Array.sort().filter(...) with zero in Javascript
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
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
});