Reputation: 2034
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 ?
Upvotes: 3
Views: 106
Reputation: 133403
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)
Upvotes: 1
Reputation: 3356
Use some()
method, which checks if any of the elements in an array pass a test (provided as a function)
var array1 = ["this", "is", "array"];
var array2 = ["this"];
var haveOne = array1.some(function (n) {
return array2.indexOf(n) >= 0;
});
console.log(haveOne);
Upvotes: 2
Reputation: 4845
In a first approach one simple loop is fine:
version 1
function intersect(arr1, arr2) {
for(var i =0; i < arr1.length; ++i)
if(arr2.indexOf(arr1[i]) >= 0))
return true;
}
version2
But if arr2
is much larger than arr1
, it would be worth considering inverting the loops order (by a runtime check):
function intersect(arr1, arr2) {
if(arr1.length < arr2.length) {
return intersect(arr2, arr1);
}
for(var i =0; i < arr1.length; ++i)
if(arr2.indexOf(arr1[i]) >= 0))
return true;
return false;
}
Worth time execution time would be the same but with better average due to better memory access (since small array will fit in cache while large one won't).
It would even better if the small array was a litteral object, since key lookup on an object is much faster than indexOf on an array.
function intersect2(arr1, arr2) {
if(arr1.length >= threshold || arr2.length <= threshold) { // to be experimented
return intersect(arr1, arr2);
}
var keys = {};
for(var i = 0; i < arr1.length; ++i) {
keys[arr[i]] = true;
}
for(var i = 0; i < arr2.length; ++i) {
if(keys[arr2.length])
return true;
}
return false;
}
Upvotes: 0
Reputation: 2993
Just find the Intersection between these array. see below example
<script>
var alpha = ["this", "is", "array"],
beta = ["this"];
$.arrayIntersect = function(a, b)
{
return $.grep(a, function(i)
{
return $.inArray(i, b) > -1;
});
};
console.log( $.arrayIntersect(alpha, beta) );
</script>
Upvotes: 0