Why 0 is not returned by the following filter ?
[0, 5, 4].sort().filter(function(i){return i}) // returns : [4, 5]
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.
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.
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 .
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 :
true
to keep the element, false
otherwise.Example :
[0, 5, 4].sort().filter(function(i){
return true // returning true to keep i element
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With