
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Array Elements for Equality in 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
Advertisements