
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
Equality 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 −
arr1[i][j] === arr2[i][j]
The above should yield true for all i between [0, number of rows] and j between [0, number of columns]
Example
Let’s write the code for this function −
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++){ for(j = 0; j < first[i].length; j++){ if(first[i][j] !== second[i][j]){ return false; }; }; }; return true; }; console.log(areEqual(arr1, arr2));
Output
The output in the console −
true
Advertisements