If you have unsorted arrays with different lengths, this will work too.
Create a function called intersect for example:
function intersect(arr1,arr2){
//We need to know which array is the shortest to avoid useless loops
if(arr2.length<arr1.length){
var temp = arr1;
arr1 = arr2;
arr2 = temp;
}
// Now, we are sure arr1 is the shortest
var result = [];
for(var i = 0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i])>-1) result.push(arr1[i]);
}
return result;
}
This function takes 2 arrays as parameters, and no need to worry about their order.
Then you can call it and see the results:
var arr1 = [1,2,3,4,5];
var arr2 = [4,5,6,7,8,9,10,12];
var inter = intersect(arr1,arr2);
alert(inter);
JS Fiddle Demo
1
solved check if item in array1 exist in array2 [closed]