kennymkchan / interview-questions-in-javascript

A mostly reasonable collection of technical software development interview questions solved in Javascript
MIT License
3.61k stars 441 forks source link

Intersection of two Arrays #36

Open hrinal1994 opened 4 years ago

hrinal1994 commented 4 years ago

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)]);

}