How to check whether a matrix is a square matrix in JavaScript

1 Answer

0 votes
function IsSquareMatrix(matrix) {
    const len = matrix.length;
 
    if (!Array.isArray(matrix) || !matrix.every(row => Array.isArray(row) && row.length === len)) {
        return false;
    }
 
    return true;
}
 
const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
 
 if (IsSquareMatrix(matrix)) {
    console.log("The matrix is a square matrix.");
}
else {
    console.log("The matrix is not a square matrix.");
}
 

 
/*
run:
 
The matrix is a square matrix.
 
*/

 



answered 1 day ago by avibootz
...