How to useFor Looping in Javascript

In this approach, we use the for loop in JavaScript to go through the element of both the input matrices of (mat1 and mat2). Then we are comparing the values of the adjacent elements. While comparing this, if the elements are not same then the value of same variable is updated as false and the loop is break. If the same value is true then this results into the output of Identical Matrices.

Example: In this example, we will see the use of for loop in JavaScript.

Javascript




let mat1 = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]
];
let mat2 = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]
];
 
let same = true;
 
for (let i = 0; i < mat1.length; i++) {
    for (let j = 0; j < mat1[i].length; j++) {
        if (mat1[i][j] !== mat2[i][j]) {
            same = false;
            break;
        }
    }
}
 
if (same) {
    console.log("Both Matrices are Identical");
} else {
    console.log("Both Matrices are not Identical");
}


Output

Both Matrices are Identical

JavaScriptProgram to Check Two Matrices are Identical or Not

We have given two matrices with the data as the input and the task is to check whether these input matrices are identical/same or not. When the number of rows and columns and the data elements are the same, the two matrices are identical. Below is the Example for better understanding:

Example:

So to check whether the input matrices are identical or not in JavaScript, we have three different approaches that are listed below:

Table of Content

  • Using For Looping
  • Using JSON.stringify() Method
  • Using every() and flat() Methods

So lets see each of the approach with its implementation:

Similar Reads

Approach 1: Using For Looping

...

Approach 2: Using JSON.stringify() Method

In this approach, we use the for loop in JavaScript to go through the element of both the input matrices of (mat1 and mat2). Then we are comparing the values of the adjacent elements. While comparing this, if the elements are not same then the value of same variable is updated as false and the loop is break. If the same value is true then this results into the output of Identical Matrices....

Approach 3: Using every() and flat() Methods

...

Contact Us