Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 493
benek Avatar asked Apr 15 '14 16:04

benek


People also ask

How do you sort a filter in JavaScript?

Simply you can use lodash method for sort by anything that you want to sort by fileName, number, etc. The OP's desired output includes filtering out duplicates, which is missing.

What is filter () in JavaScript?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

How sort method works in JavaScript?

When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b . If the result is positive b is sorted before a .


2 Answers

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.

like image 89
Kyle Avatar answered Oct 04 '22 18:10

Kyle


.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
});
like image 45
Malik Khalil Avatar answered Oct 04 '22 18:10

Malik Khalil