Search code examples
javascriptfilterlodash

How to include null/undefined values when using lodash filter


I would like to filter on a particular object property. If that property is false OR undefined/null, I want it included. In the example below, I am summing by the deliciousRating as long as isBruised is not true. However, I can't figure out how to include the undefined/null value.

var apples = [
    {isBruised: true, deliciousRating: 1},
    {isBruised: false, deliciousRating: 10},
    {deliciousRating: 9}
];

_.sumBy(_.filter(apples, ['isBruised', false]), 'deliciousRating');

I would like this to return 19, but currently it is only getting the deliciousRating from apples[1].


Solution

  • Use _.reject() instead of _.filter(). The _.reject() method is...

    The opposite of _.filter; this method returns the elements of collection that predicate does not return truthy for.

    var apples = [
        {isBruised: true, deliciousRating: 1},
        {isBruised: false, deliciousRating: 10},
        {deliciousRating: 9}
    ];
    
    var result = _.sumBy(_.reject(apples, 'isBruised'), 'deliciousRating');
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    And in vanilla JS, you can use Array#reduce to sum just the items that are not bruised:

    var apples = [
        {isBruised: true, deliciousRating: 1},
        {isBruised: false, deliciousRating: 10},
        {deliciousRating: 9}
    ];
    
    var result = apples.reduce(function(s, o) {
      return o.isBruised ? s : s + o.deliciousRating;
    }, 0);
    
    console.log(result);