Filter out an array with null values, underscore

前端 未结 5 1417
情歌与酒
情歌与酒 2021-02-11 17:54

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:37

    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:40

    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:45

    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

    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)
  • 2021-02-11 18:59

    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)
提交回复
热议问题