Skip to content
Advertisement

Check if arrays contain shared elements regardless of index

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement