Having some problems here with arrays. I basically want to loop through array1
, check which elements in that array exist in array2
and then return a new array containing all matches.
How would one do that?
Having some problems here with arrays. I basically want to loop through array1
, check which elements in that array exist in array2
and then return a new array containing all matches.
How would one do that?
This code is in pure javascript not with library
var fruits1 = ["Banana", "Pear"];
var fruits2 = ["Banana", "Orange", "Apple", "Mango"];
var fruits3 = [];
for (i=0; i< fruits1.length; i++)
if (fruits2.indexOf(fruits1[i]) > -1)
fruits3.push(fruits1[i]);
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);
Vanilla Javascript
for(var x=0;x<array1.length;x++){
for(var y=0;y<array2.length;y++){
if ( array1[x] == array2[y] ) array3.push(array1[x]);
}
}
Jquery version
$.each(array1, function(k,v){
$.each(array2, function(k2,v2){
if ( v == v2 ) array3.push(v2);
});
});