Reputation: 12718
I'd like to check if two arrays share elements regardless of order.
Given
array A: ['hello', 'how', 'are', 'you']
array B: ['how', 'are', 'hello']
Will return matches for 'hello', 'how', and 'are'
There seems to be something for PHP, array_intersect()
(Check if array contains elements having elements of another array), but nothing for JavaScript.
I would use in
if the values were in an object, but they are not:
if (key in obj) {
}
I could also do array.sort()
to both arrays, but it's not guaranteed that both arrays will have same number of values. Therefore even if they are sorted, the compared indices would be off anyway.
How can I do this in JavaScript?
Upvotes: 3
Views: 2878
Reputation: 178
In ES6 syntax:
var intersection = arr1.filter( e => arr2.includes( e ) )
Upvotes: 0
Reputation: 490
In this approach, the first array is converted into a map, for fast lookup.
The second array is matched against the first.
The complexity is O(a) + O(b).
Pro: Elegance.
Con: Matching is continued after the overlap is detected.
function array_overlap(a, b) {
const lookup = a.reduce((m, n) => (m[n]=true, m), {});
const status = b.reduce((m, n) => (lookup[n] || m), false);
return status;
}
Upvotes: 0
Reputation: 2335
Considering performance I'd convert one of the array to an object, and then check intersection by traversing the other.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var set = {};
var intersect = [];
for (var i = 0; i < arr1.length; i++)
set[arr1[i]] = true;
for (var i = 0; i < arr2.length; i++)
if (set[arr2[i]]) intersect.push(arr2[i]);
But this method will ignore duplicate items in the arrays. And this may seem verbose compared to the filter and find solution. This may be helpful if you're doing intersection of large arrays.
Upvotes: 0
Reputation: 87203
You can use filter to check if the same element is present in the other array.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.filter(function(e) {
return arr2.indexOf(e) > -1;
});
console.log(commonElements);
You can also define this function on Array prototype
Array.prototype.intersection = function(arr) {
return this.filter(function(e) {
return arr.indexOf(e) > -1;
});
};
var arr1 = ['hello', 'how', 'are', 'you'],
arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.intersection(arr2);
console.log(commonElements);
Upvotes: 4