underscore.js filter an array of objects, based on another

javascript, underscore.js

Solution

Just create a "set" of the valid ids and use that "set" to do the filtering:

var aaa = [
    {name: "AAA", id: 845},
    {name: "BBB", id: 839},
    {name: "CCC", id: 854}
];
var bbb = [
    {id: 839},
    {id: 854}
];

var ids = {};
_.each(bbb, function (bb) { ids[bb.id] = true; });

var out = _.filter(aaa, function (val) {
    return ids[val.id];
}, bbb);

Filling `ids` is fast, it's in n * amortized O(1), i.e O(n). Same holds for the filtering.

If you use `each(…)` in the inner loop, you will have O(n²). For bigger data sets this would become very slow. Also the additional nesting make the code more difficult to read/understand at first glance.

See that code snipped in action: http://jsfiddle.net/SMtX5/

Problem

I am trying to filter an array of objects, based on another. The common property id `id`. I am not sure filter + each is the best way to do it or map reduce. Anyway, below code doesn't work as `out` is empty list. ``` var aaa = [ {name: "AAA", id: 845}, {name: "BBB", id: 839}, {name: "CCC", id: 854} ]; var bbb = [ {id: 839}, {id: 854} ]; var out = _.filter(aaa, function(val){ return _.each(this, function(val2){ return val['id'] === val2['id'] }); }, bbb); ```

Original source

Related problems