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

前端 未结 5 847
情深已故
情深已故 2020-12-10 13:44

Why 0 is not returned by the following filter ?

[0, 5, 4].sort().filter(function(i){return i}) // returns : [4, 5]
5条回答
  •  余生分开走
    2020-12-10 14:26

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

提交回复
热议问题