Comparison of arrays by using forEach method.

This question is most commonly asked in interviews.

There are different ways to achieve these, But I’m showing here one of them.

First array

const arr1= [1,5,6,7,5,6,5,56,11,78,9789,8679,7,10];

Second array

const arr2= [1,5,6,7,8,5,6,7,8,10,11,78];

Now we are writing the compare function it helps us to compare above two arrays.

Let’s start

Step 1: We need to declare the function with two parameters.

function compare(arr1,arr2){ }

Step 2: We need to Initialize an empty array.

function compare(arr1,arr2){

const finalarray =[];

}

Step 3: We are taking the help of forEach method in Array.protoype.forEach().

The forEach() method takes the callback function and executes it each and every element in the array.

In above code first, we are chaining arr1 with forEach() method gives us back each element in the arr1 at the end we are returning the second arr chaining with forEach() method it gives us back elements in the second array which is e2 then we started comparing first element and the second element. If something is true we started entering into the if block.

Step 4: Returning the final Answer.

Result

Why we get repeated elements?

Because we are using repeated elements in the both arrays check out arr1 and arr2.

To get the Unique elements from the array we need to do few changes to our function.

function compare(arr1,arr2){



const objMap={};



arr1.forEach((e1)=>arr2.forEach((e2)=> {if(e1 === e2){

objMap[e1]=objMap[e1]+1||1 ;

}

}

)); console.log(Object.keys(objMap).map(e=>Number(e)));

}

Second way

function compare(arr1,arr2){



if(!arr1 || !arr2) return



let result;



arr1.forEach((e1,i)=>arr2.forEach(e2=>{



if(e1.length > 1 && e2.length){

result = compare(e1,e2);

}else if(e1 !== e2 ){

result = false

}else{

result = true

}

})

)



return result



} compare([1,2,3],[1,2,3])

// true compare([1,2],[1,2,3])

//false

The second method even works with nested arrays comparison

compare([1, 2, [3, 4,5]],[1, 2, [3, 4,5]])

//true compare([[1,2],[3,4]],[[1,2],[3,4]])

// false compare([[1,2],[3,4]],[[1,2],[3,4,6]])

//false

Other interesting articles