var array1 = [];
var array2 = [];
intersect(array1, array2);
//Function to compare the intersection of two sorted arrays
//Input : 2 arrays comtainig integers
//Output : An integer array containing the intersection of two input arrays
function intersect(xs, ys){
var length1 = xs.length;
var length2 = ys.length;
var mainarray;
var comparearray;
var hasharray = [];
var resultarray = [];
//Compare which input array is longer and using that as main array to run the comparison
if(length1 < length2) {
mainarray = ys;
comparearray = xs;
}
else {
mainarray = xs;
comparearray = ys;
}
//This iteration will run on both the main array and compare array
//The array 'hasharray' will behave as a hashmap and index of this array is the key and the value is the value from main or compare array.
//The array 'resultarray' will hold the result
for(var iterator = 0, result=0; iterator < mainarray.length; iterator++) {
if(hasharray[mainarray[iterator]] != mainarray[iterator]) {
hasharray[mainarray[iterator]] = mainarray[iterator];
}
else {
resultarray[result++] = mainarray[iterator];
alert(resultarray[result-1]);
}
//Since compare array is of smaller length, the comparison should stop when the all the elements in this array are processed.
if(iterator < comparearray.length ) { if(hasharray[comparearray[iterator]] != comparearray[iterator]) {
hasharray[comparearray[iterator]] = comparearray[iterator];
}
else {
resultarray[result++] = comparearray[iterator];
alert(resultarray[result-1]);
}
}
}
return resultarray;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.