Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute intersection of two arrays in JavaScript [duplicate]

Given two arrays of unequal length:

var arr1 = ["mike", "sue", "tom", "kathy", "henry"]; //arr1.length = 5 var arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"]; //arr2.length = 7 

How can I find the values common to both arrays? In this case "sue" and "kathy" should be returned.

like image 257
Justin Avatar asked Apr 26 '13 01:04

Justin


2 Answers

Here is an intersection function based on Array.prototype.filter

function intersect(a, b) {     var t;     if (b.length > a.length) t = b, b = a, a = t; // indexOf to loop over shorter     return a.filter(function (e) {         return b.indexOf(e) > -1;     }); }  var arr1 = ["mike", "sue", "tom", "kathy", "henry"];     arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];  intersect(arr1, arr2); // ["sue", "kathy"] 

You might also want to consider the following

var arr1 = ['sue', 'sue', 'kathy'],     arr2 = ['kathy', 'kathy', 'sue']; 

The above would now give ["sue", "sue", "kathy"]. If you don't want duplicates you could do a further filter on this. This would also standardise results. i.e.

return a     .filter(/* .. */) // same as before     .filter(function (e, i, c) { // extra step to remove duplicates         return c.indexOf(e) === i;     }); 

Adding this will now return the same result as the previous arrays (["sue", "kathy"]), even though there were duplicates.

like image 140
Paul S. Avatar answered Sep 19 '22 17:09

Paul S.


You could use Array.filter:

var result = arr1.filter(function(n) {   return arr2.indexOf(n) > -1; }); 
like image 22
xdazz Avatar answered Sep 20 '22 17:09

xdazz