Search code examples
lodash

_.filter array of objects using a property with either value


I'd like to filter an array of objects I only want objects with status equals to 0 or 1 this is my code.

_.filter(array, { status: 1 || 0 });

but its not working it only fetches objects with status equals to 1.

_.filter(array, function (a) { return a.status === 1 || a.status === 0 });

Works but I'd like to know the shorthand method. How do I accomplish this without using the function method?

Edit: Okay, got it. What I was actually looking for is arrow function.

_.filter(array, a => a.status === 1 || a status === 0);

Solution

  • your shorthand is not valid, read more about _.matches predicate, in your case use function

    _.filter(array, item => _.includes([0, 1], item.status))