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);
Underscore.js is a lightweight JavaScript library and not a complete framework that was written by Jeremy Ashkenas that provides utility functions for a variety of use cases in our day-to-day common programming tasks. Array is a single variable that is used to store different elements.
Filter an Array of Objects in JavaScript. JavaScript arrays have a filter () method that let you create a new array containing only elements that pass a certain test. In other words, filter () gives you a new array containing just the elements you need.
The filterObjsinArr function takes in an array of objects: arr and a selection array as arguments. It maps through arr to get individual objects. For each object, it loops through each property, checking if it exists in the selection array. This second method is shorter in terms of lines of code.
Show activity on this post. The simplest way to filter is to use the array's filter () function, similar to this: Show activity on this post. You can use array.filter () with few conditions to get the output you want. Also i have corrected your JSON. Show activity on this post. Show activity on this post.
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/
you can use _.find
to filter:
_.filter(aaa, function(a){ return _.find(bbb, function(b){ return b.id === a.id; }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With