JSFiddle - React, Tailwind, and code Playground

by Siva Subramaniam

JavaScript

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;

}