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
Checking for the similarity of two 2-D arrays in JavaScript
We are required to write a JavaScript function that takes in two 2-D arrays and returns a boolean based on the check whether the arrays are equal or not. The equality of these arrays, in our case, is determined by the equality of corresponding elements.
Both the arrays should have same number of rows and columns. Also, arr1[i][j] === arr2[i][j] should yield true for all i between [0, number of rows] and j between [0, number of columns]
Method 1: Basic Nested Loop Approach
This method compares each element position by position using nested loops:
const arr1 = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
];
const arr2 = [
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
];
const areEqual = (first, second) => {
const { length: l1 } = first;
const { length: l2 } = second;
if(l1 !== l2){
return false;
}
for(let i = 0; i < l1; i++){
// Check if row lengths are equal
if(first[i].length !== second[i].length){
return false;
}
for(let j = 0; j < first[i].length; j++){
if(first[i][j] !== second[i][j]){
return false;
}
}
}
return true;
};
console.log(areEqual(arr1, arr2));
true
Method 2: Using JSON.stringify
A simpler approach converts both arrays to JSON strings for comparison:
const arr3 = [[1, 2], [3, 4]];
const arr4 = [[1, 2], [3, 4]];
const arr5 = [[1, 2], [3, 5]];
const areEqualJSON = (first, second) => {
return JSON.stringify(first) === JSON.stringify(second);
};
console.log(areEqualJSON(arr3, arr4)); // Same arrays
console.log(areEqualJSON(arr3, arr5)); // Different arrays
true false
Testing with Different Cases
Let's test our function with various scenarios:
// Different dimensions
const diffRows = [[1, 2], [3, 4]];
const moreRows = [[1, 2], [3, 4], [5, 6]];
// Different column lengths
const jaggedArr1 = [[1, 2, 3], [4, 5]];
const jaggedArr2 = [[1, 2, 3], [4, 5, 6]];
console.log("Different row count:", areEqual(diffRows, moreRows));
console.log("Different column lengths:", areEqual(jaggedArr1, jaggedArr2));
console.log("Empty arrays:", areEqual([], []));
Different row count: false Different column lengths: false Empty arrays: true
Comparison of Methods
| Method | Performance | Handles Edge Cases | Code Complexity |
|---|---|---|---|
| Nested Loops | Better for large arrays | Explicit handling needed | More complex |
| JSON.stringify | Slower for large arrays | Automatic | Simple one-liner |
Conclusion
Both methods effectively compare 2-D arrays. Use nested loops for better performance with large datasets, or JSON.stringify for simpler code when performance isn't critical.
