interview-questions-in-javascript icon indicating copy to clipboard operation
interview-questions-in-javascript copied to clipboard

Intersection of two Arrays

Open hrinal1994 opened this issue 3 years ago • 0 comments

Find below optimized code for intersection of two arrays:

var firstArray = [2, 2, 4, 1,5,2,3,6,4,22,2]; var secondArray = [1, 2, 0, 2];

intersection(firstArray, secondArray); // [2, 1]

function intersection(firstArray, secondArray) {

let finalArray=[];

for(let i=0;i<firstArray.length;i++){

if(secondArray.indexOf(firstArray[i])> -1){

  
  finalArray.push(firstArray[i]);
}

}

console.log([... new Set(finalArray)]);

}

hrinal1994 avatar Sep 14 '20 12:09 hrinal1994