Suppose, we have a 2-D array representing a square matrix like this −
const arr = [ [1, 3, 4, 2], [4, 5, 3, 5], [5, 2, 6, 4], [8, 2, 9, 3] ];
We are required to write a function that takes in this array and returns the product of the element present at the principal Diagonal of the matrix.
For this array the elements present at the principal diagonal are −
1, 5, 6, 3
Hence the output should be −
90
Example
Following is the code −
const arr = [ [1, 3, 4, 2], [4, 5, 3, 5], [5, 2, 6, 4], [8, 2, 9, 3] ]; const diagonalProduct = arr => { let product = 1; for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j++){ if(i === j){ product *= arr[i][j]; }; }; }; return product; }; console.log(diagonalProduct(arr));
Output
Following is the output in the console −
90