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.
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.
You could use Array.filter:
var result = arr1.filter(function(n) { return arr2.indexOf(n) > -1; });
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