Equality of two 2-D arrays - 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
Updated on: 2020-09-15T09:51:57+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements