Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding intersection of two arrays in Node.js [duplicate]

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?

like image 337
Silent User Avatar asked Nov 29 '22 17:11

Silent User


2 Answers

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

_(a).intersection(b)

or

_.intersection(a, b)
like image 199
Asherah Avatar answered Dec 01 '22 05:12

Asherah


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.

like image 43
slowpoison Avatar answered Dec 01 '22 05:12

slowpoison