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

前端 未结 5 836
情深已故
情深已故 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:15

    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);
    
    0 讨论(0)
  • 2020-12-10 14:19

    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.

    0 讨论(0)
  • 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
    });
    
    0 讨论(0)
  • 2020-12-10 14:31

    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 讨论(0)
  • 2020-12-10 14:32

    Try this:

    [0, 5, 4].sort().filter(function(i){
        return ((i) ? i : !i);
    })
    
    0 讨论(0)
提交回复
热议问题