Filter out an array with null values, underscore

前端 未结 5 1421
醉话见心
醉话见心 2021-02-11 18:32

I have this array:

[null, {name:\'John\'}, null, {name:\'Jane\'}]

I want to remove the null values. Is there an easy way to do this with unders

相关标签:
5条回答
  • 2021-02-11 18:36

    The best solution is to use compact, but the default behaviour of the filter function when you don't include a specific truth test function is to remove falsy values

    For example:

    _.filter([null, {name:'John'}, null, {name:'Jane'}])
    

    returns a object array without the nulls:

    [{name:'John'}, {name:'Jane'}]
    
    0 讨论(0)
  • 2021-02-11 18:41

    This will work for you

    Filter

    _.filter(arr,function (value) {
        return value!==null;
    })
    

    Reject

    _.reject(arr,function (value) {
        return value===null;
    })
    
    0 讨论(0)
  • 2021-02-11 18:45

    If the array contains either nulls or objects then you could use compact:

    var everythingButTheNulls = _.compact(list);
    

    NB compact removes all falsy values so if the array could contain zeros, false etc then they would also be removed.

    Could also use reject with the isNull predicate:

    var everythingButTheNulls = _.reject(array, _.isNull);
    
    0 讨论(0)
  • 2021-02-11 18:46

    Try using _.without(array, *values) it will remove all the values that you don't need. In your case *values == null

    http://underscorejs.org/#without

    0 讨论(0)
  • 2021-02-11 18:57

    From underscore documentation

    without_.without(array, *values) 
    Returns a copy of the array with all instances of the values removed.
    

    So just use this method

    var a = [null, {name:'John'}, null, {name:'Jane'}]
    a = _.without(a, null);
    
    0 讨论(0)
提交回复
热议问题