- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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
- Related Articles
- Checking the equality of array elements (sequence dependent) in JavaScript
- Equality of corresponding elements in JavaScript
- How to compare String equality in Java?
- Java Program to compare strings for equality
- How to compare two lists for equality in C#?
- How to compare two ArrayList for equality in Java?
- Strict equality vs Loose equality in JavaScript.
- Compare array of objects - JavaScript
- loose equality in JavaScript
- Equality of two arrays JavaScript
- object.is() in equality comparison JavaScript
- MongoDB aggregation with equality inside array?
- Shift certain array elements to front of array - JavaScript
- Accumulating array elements to form new array in JavaScript
- How to replace elements in array with elements of another array in JavaScript?

Advertisements