Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Compare array elements to equality - JavaScript
In JavaScript, you can compare array elements at corresponding positions to count how many values match. This is useful for analyzing similarities between two arrays in a sequence-dependent manner.
For example, if you have two arrays:
const arr1 = [4, 7, 4, 3, 3, 3, 7, 6, 5]; const arr2 = [6, 5, 4, 5, 3, 2, 5, 7, 5];
The function should compare arr1[0] with arr2[0], arr1[1] with arr2[1], and so on. In this case, positions 2, 4, and 7 have matching values, so the result is 3.
Using a For Loop
The most straightforward approach uses a for loop to iterate through both arrays simultaneously:
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
3
Using Array.reduce()
A more functional approach uses the reduce() method:
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) => {
return arr1.reduce((count, value, index) => {
return value === arr2[index] ? count + 1 : count;
}, 0);
};
console.log(correspondingEquality(arr1, arr2));
3
Handling Different Array Lengths
To handle arrays of different lengths, compare only up to the shorter array's length:
const arr1 = [1, 2, 3, 4];
const arr2 = [1, 2, 5];
const correspondingEquality = (arr1, arr2) => {
let res = 0;
const minLength = Math.min(arr1.length, arr2.length);
for(let i = 0; i
2
Comparison
| Method | Readability | Performance | Handles Different Lengths |
|---|---|---|---|
| For Loop | Good | Fast | With modification |
| Array.reduce() | Excellent | Slightly slower | With modification |
Conclusion
Use a for loop for simple array comparison when performance matters, or Array.reduce() for a more functional programming approach. Always consider handling arrays of different lengths in production code.
