lodash: filter array of objects with a different array of objects

Here is cleaner way i can think of:

var result = _.flatten(_.map(others, function(item){
  return _.filter(users, item);
}));

Edit: Apologies JS Bin output was obfuscating the nested array.


var result = _.flatten(_.map(others, function(other){return _.where(users, other);}));

You can index the others, and then get the desired results without having to nest loops. It should be a relatively efficient solution, regardless of the amount of data:

// index others by "user + age"
var lookup = _.keyBy(others, function(o) { return o.user + o.age.toString() });
// find all users where "user + age" exists in index, one loop, quick lookup. no nested loops
var result = _.filter(users, function(u) {
    return lookup[u.user + u.age.toString()] !== undefined;
});

This gives the same result:

[
  { 'user': 'fred', 'age': 60, 'active': false },
  { 'user': 'fred', 'age': 70, 'active': false },
  { 'user': 'fred', 'age': 22, 'active': false }
];

Interestingly, your original solution was the most performant of all of these answers.

http://jsperf.com/testingdiwq

The performance concerns are pretty negligible here. In most cases, the DOM interaction is the main performance bottleneck of the front-end. If you were to run this against huge datasets and noticed the locking, you'd definitely want to optimize it further by using for loops instead of iterating with lodash functions.... but you won't typically come across that kind of data in JavaScript... SQL and others would handle it better.


Using ES6 fat arrows and lodash's reject:

const result = _.reject(users, (item) => _.find(others, { user: item.user }));