Suppose, we have a square matrix represented by a 2-D array in JavaScript like this −
const arr = [ [1, 3, 5], [3, 5, 7], [2, 4, 2] ];
We are required to write a JavaScript function that takes in one such array.
The function should return the difference between the sum of elements present at the diagonals of the matrix.
Like for the above matrix, the calculations will be −
|(1+5+2) - (5+5+2)| |8 - 12| 4
Example
Following is the code −
const arr = [ [1, 3, 5], [3, 5, 7], [2, 4, 2] ]; const diagonalDiff = arr => { let sum = 0; for (let i = 0, l = arr.length; i < l; i++){ sum += arr[i][l - i - 1] - arr[i][i]; }; return Math.abs(sum); } console.log(diagonalDiff(arr));
Output
This will produce the following output on console −
4