Calculate Subtraction of diagonals-summations in a two-dimensional matrix using JavaScript

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]
];
console.log(arr);
[ [ 1, 3, 5 ], [ 3, 5, 7 ], [ 2, 4, 2 ] ]

We need to write a JavaScript function that calculates the absolute difference between the sum of elements on the two diagonals of the matrix.

Understanding the Diagonals

In a square matrix, there are two diagonals:

  • Primary diagonal: Elements from top-left to bottom-right (arr[0][0], arr[1][1], arr[2][2]...)
  • Secondary diagonal: Elements from top-right to bottom-left (arr[0][n-1], arr[1][n-2], arr[2][n-3]...)

For the above matrix, the calculations will be:

Primary diagonal: 1 + 5 + 2 = 8
Secondary diagonal: 5 + 5 + 2 = 12
Absolute difference: |8 - 12| = 4

Solution

Here's the complete implementation:

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));
4

How It Works

The function uses a single loop to calculate both diagonal sums simultaneously:

  • arr[i][i] accesses the primary diagonal elements
  • arr[i][l - i - 1] accesses the secondary diagonal elements
  • The difference is accumulated in the sum variable
  • Math.abs() returns the absolute value of the final difference

Alternative Approach

You can also calculate the sums separately for better readability:

const diagonalDiffSeparate = arr => {
   let primarySum = 0;
   let secondarySum = 0;
   
   for (let i = 0; i < arr.length; i++) {
      primarySum += arr[i][i];
      secondarySum += arr[i][arr.length - i - 1];
   }
   
   return Math.abs(primarySum - secondarySum);
}

console.log(diagonalDiffSeparate(arr));
4

Conclusion

Both approaches efficiently calculate the diagonal difference in O(n) time complexity. The first method is more concise, while the second is more readable and easier to understand.

Updated on: 2026-03-15T23:19:00+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements