# Checking for particular types of matrix in JavaScript

JavascriptWeb DevelopmentFront End Technology

## Problem

We are required to write a JavaScript function that takes in a 2-D array of literals, arr, as the first and the only argument.

Our function should check if every diagonal from top-left to bottom-right has the same element.

If it is so, we should return true, false otherwise.

For example, if the input to the function is

Input

const arr = [
[6, 7, 8, 9],
[2, 6, 7, 8],
[1, 2, 6, 7],
];

Output

const output = true;

Output Explanation

In the above array, the diagonals are −

, [2,2], [6,6,6], [7,7,7], [8,8], 

In each diagonal all elements are the same, so the answer is True.

## Example

Following is the code −

Live Demo

const arr = [
[6, 7, 8, 9],
[2, 6, 7, 8],
[1, 2, 6, 7],
];
const checkMatrix = (arr = []) => {
const validate = (row, col) => {
while (
row < arr.length
&& col < arr.length
&& arr[row + 1]
&& arr[row + 1][col + 1] !== undefined
) {
if (arr[row + 1][col + 1] !== arr[row][col]) {
return false
}
row += 1
col += 1
}
return true
}
for (let i = 0; i < arr.length; i++) {
if (!validate(0, i)) {
return false
}
}
for (let i = 0; i < arr.length; i++) {
if (!validate(i, 0)) {
return false
}
}
return true
}
console.log(checkMatrix(arr));

## Output

true