I would like to filter a collection using array of property value. Given an array of IDs, return objects with matching IDs. Is there any shortcut method using lodash
/underscore
?
var collections = [{ id: 1, name: 'xyz' },
{ id: 2, name: 'ds' },
{ id: 3, name: 'rtrt' },
{ id: 4, name: 'nhf' },
{ id: 5, name: 'qwe' }];
var ids = [1,3,4];
// This works, but any better way?
var filtered = _.select(collections, function(c){
return ids.indexOf(c.id) != -1
});
This worked great for me:
I like jessegavin's answer, but I expanded on it using lodash-deep for deep property matching.
jsFiddle
If you don't trust lodash-deep or you want support for properties that have dots in their names, here's a more defensive and robust version:
If you're going to use this sort of pattern a lot, you could create a mixin like the following, though, it isn't doing anything fundementally different than your original code. It just makes it more developer friendly.
Then you can use it like this.
Update - This above answer is old and clunky. Please use the answer from Adam Boduch for a much more elegant solution.
These answers didn't work for me, because I wanted to filter on a non-unique value. If you change
keyBy
togroupBy
you can get by.My initial use was to drop things, so I switched out
pick
withomit
.Thanks Adam Boduch for the starting point.
I noticed many of these answers are outdated or contain auxiliary functions not listed in Lodash documentation. The accepted answer includes deprecated function
_.contains
and should be updated.So here is my ES6 answer.
Based on Lodash v4.17.4
And invoked as such:
A concise lodash solution that uses indexBy() and at().