How to check a value in another table and vice versa

advertisements

I have two arrays and I dont know the values of the array before I ant to test anything I mean lenght of the array is dynamic

My question is How to check two array have ateast one common value

suppose I have two arrays like this case 1:

array1 = ["this", "is", "array"]
array2 = ["this"]

when we compare these array by a function like campareArray(array1, array2) should return true, and the same array like this:

array1 = ["this"]
array2 = ["this", "is", "array"]

should return true

what will be the efficient way? we can check array lenght and check indexof from big to small there are any other good way ?


You can use filter() method and get the intersection of the two arrays.

var array1 = ["this", "is", "array"],
  array2 = ["this"];

var result = array1.filter(function(n) {
  return array2.indexOf(n) != -1;
});
console.log("Arrays have common element: " + !!result.length)
console.log(result)