4

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?

1
  • 2
    I've seen this question twice in the last few days, is there a CS class handing this out as an assignment? Commented May 3, 2012 at 3:03

2 Answers 2

14

Underscore.js can calculate the intersection of n arrays. Hence:

_(a).intersection(b)

or

_.intersection(a, b)
Sign up to request clarification or add additional context in comments.

Comments

10

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.

1 Comment

For a faster version, make sure you run the for loop over the shorter array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.