Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash Filter collection using array of values

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
});
like image 425
Amitava Avatar asked Jun 22 '13 14:06

Amitava


2 Answers

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.

_.mixin({
  'findByValues': function(collection, property, values) {
    return _.filter(collection, function(item) {
      return _.contains(values, item[property]);
    });
  }
});

Then you can use it like this.

var collections = [
    {id: 1, name: 'xyz'}, 
    {id: 2,  name: 'ds'},
    {id: 3,  name: 'rtrt'},
    {id: 4,  name: 'nhf'},
    {id: 5,  name: 'qwe'}
];

var filtered = _.findByValues(collections, "id", [1,3,4]);

Update - This above answer is old and clunky. Please use the answer from Adam Boduch for a much more elegant solution.

_(collections)
  .keyBy('id') // or .indexBy() if using lodash 3.x
  .at(ids)
  .value();
like image 74
jessegavin Avatar answered Nov 01 '22 17:11

jessegavin


A concise lodash solution that uses indexBy() and at().

// loDash 4
_.chain(collections)
 .keyBy('id')
 .at(ids)
 .value();

// below loDash 4
_(collections)
 .indexBy('id')
 .at(ids)
 .value();
like image 48
Adam Boduch Avatar answered Nov 01 '22 17:11

Adam Boduch