Compare array elements to equality - JavaScript

We are required to write a function which compares how many values match in an array. It should be sequence dependent. That means i.e. the first object in the first array should be compared to equality to the first object in the second array and so on.

For example −

If the two input arrays are −

const arr1 = [4, 7, 4, 3, 3, 3, 7, 6, 5];
const arr2 = [6, 5, 4, 5, 3, 2, 5, 7, 5];

Then the output should be 3.

We can solve this problem simply by using a for loop and checking values at the corresponding indices in both the arrays.

Example

Following is the code −

const arr1 = [4, 7, 4, 3, 3, 3, 7, 6, 5];
const arr2 = [6, 5, 4, 5, 3, 2, 5, 7, 5];
const correspondingEquality = (arr1, arr2) => {
let res = 0;
for(let i = 0; i < arr1.length; i++){
if(arr1[i] !== arr2[i]){
continue;
};
res++;
};
return res;
};
console.log(correspondingEquality(arr1, arr2));

Output

This will produce the following output in console −

3