Possible Duplicate:
Simplest code for array intersection in JavaScript
I am writing an app with Mongodb and Nodejs. I have a 'students' collection which contains, among other things, an array with a list of all the courses (course IDs, which refer to documents in the 'courses' collection) a particular student has taken.
I have 2 students, StudentA and StudentB. I want to see if these two students took any common courses.
I have already retrieved the studentA and studentB documents from Mongodb. I want to find the intersection between these 2 arrays in Node.js app.
One approach I thought of was to go through the first array, create a hash map with the objectid as the key. Then go through the 2nd array and try to increment the value by 1. In the end, all the entries with a value of 1 are the intersecting elements.
Is there a better approach?
Underscore.js can calculate the intersection of n arrays. Hence:
_(a).intersection(b)
or
_.intersection(a, b)
Here's how
a=[1,2,3,4];
b=[3,4,5];
c=[];
j=0;
for (var i=0; i < a.length; ++i)
if (b.indexOf(a[i]) != -1)
c[j++] = a[i];
c
will contain the intersection at the end of this.
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