How to useevery() and flat() Methods in Javascript
In this approach, we are using the inbuilt method as every() and flat() in JavaScript. Here, the flat() method converts the matrices into flat arrays which consists of the elements of the matrices. Then by using the every() method, we are going through the elements of this array and checking if the elements of m1 is same as m2. If they are same then it mesna that our input matrices are same, else they are not same.
Example: In this example, we will see the use of every and flat methods 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 = (m1, m2) => m1.flat().every((val, ind) => val === m2.flat()[ind]); if (same(mat1, mat2)) { console.log( "Both Matrices are Identical" ); } else { console.log( "Both Matrices are not Identical" ); } |
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:
Contact Us