Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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); 
like image 729
bsr Avatar asked Feb 27 '13 03:02

bsr


People also ask

What is underscore array JS?

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.

How to filter an array of objects in JavaScript?

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.

How do you use filterobjsinarr?

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.

How to filter activity in a JSON array?

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.


2 Answers

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/

like image 154
kay Avatar answered Sep 28 '22 01:09

kay


you can use _.find to filter:

_.filter(aaa, function(a){     return _.find(bbb, function(b){         return b.id === a.id;     }); }); 
like image 31
anhulife Avatar answered Sep 28 '22 00:09

anhulife