For searching elements of one array inside the other, one may use the indexOf() on the target of search and run a loop on the other array elements and in each step check existence. This is trivial and my knowledge on Javascript is too. Could any one please suggest a more efficient way? Maybe even a built-in method of the language could help? Although I couldn't hit to such a method using google.
-
`indexOf` is probably as efficient as you need, but there are some other methods mentioned at http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript and possibly at http://stackoverflow.com/questions/11076067/finding-matches-between-multiple-javascript-arrays – Rhumborl Sep 24 '14 at 07:58
-
You have to use `indexOf` or a loop for a reliable cross browser solution. There are methods available in frameworks like jQuery (e.g: `inArray`), but that also make use of the same. – Diode Sep 24 '14 at 08:01
3 Answers
You can use Array.filter() internally and implement a function on Array's prototype which returns elements which are common to both.
Array.prototype.common = function(a) {
return this.filter(function(i) {
return a.indexOf(i) >= 0;
});
};
alert([1,2,3,4,5].common([4,5,6])); // "4, 5"
Again as you mention in your post, this logic also works by taking each element and checking whether it exists in the other.

- 1,031,962
- 187
- 1,923
- 1,875

- 27,240
- 14
- 77
- 101
A hair more efficient way is convert one of the arrays into a hash table and then loop through the second one, checking the presence of elements at O(1) time:
a = [1,2,3,4,5]
b = [1,7,3,8,5]
map = {}
a.forEach(function(x) { map[x] = 1 })
intersection = b.filter(function(x) { return map[x] === 1 })
document.write(JSON.stringify(intersection))
This only works if elements in question are primitives. For arrays of objects you have to resort to the indexOf
method.
ES6 ("Harmony") does support Set
, but strangely not set operations (union, intersection etc), so these should be coded by hand:
// Firefox only
a = [1,2,3,4,5]
b = [1,7,3,8,5]
sa = new Set(a)
sb = new Set(b)
sa.forEach(function(x) {
if (!sb.has(x))
sa.delete(x);
});
document.write(uneval([...sa]))

- 211,518
- 52
- 313
- 390
JavaScript's arrays don't have a method that does intersections. Various libraries provide methods to do it (by looping the array as you describe), including Underscore and PrototypeJS (and others, I'm sure).

- 1,031,962
- 187
- 1,923
- 1,875