Search code examples
arrayswhere-clauselodashempty-list

lodash findwhere with empty array


I'm stuck with something appening when using lodash _.findWhere (the same with _.where)

var testdata = [
    {
        "id": "test1",
        "arr": [{ "a" : "a" }]
    },
    {
        "id": "test2",
        "arr": []
    }
];

_.findWhere(testdata, {arr : [] });
//--> both elements are found

I'm trying to extract elements from testdata where arr is an empty array, but _.where also includes elements with non-empty arrays.

I've also test with _.matchesProperty, but no way, same result.

I'm sure I'm missing something easy, but cannot see what :s

please help :)

http://plnkr.co/edit/DvmcsY0RFpccN2dEZtKn?p=preview


Solution

  • For this, you want to isEmpty():

    var collection = [
        { id: 'test1', arr: [ { a : 'a' } ] },
        { id: 'test2', arr: [] }
    ];
    
    _.find(collection, function(item) {
        return _.isEmpty(item.arr);
    });
    // → { id: 'test2', arr: [] }
    
    _.reject(collection, function(item) {
        return _.isEmpty(item.arr);
    });
    // → [ { id: 'test1', arr: [ { a : 'a' } ] } ]
    

    You can also use higher order functions, like flow(), so can abstract your callbacks:

    var emptyArray = _.flow(_.property('arr'), _.isEmpty),
        filledArray = _.negate(emptyArray);
    
    _.filter(collection, emptyArray);
    // → [ { id: 'test2', arr: [] } ]
    
    _.filter(collection, filledArray);
    // → [ { id: 'test1', arr: [ { a : 'a' } ] } ]