Diagonal Sum of a matrix in Javascript

This blog will teach you how to find the sum of the elements that are on the diagonal of a 2-dimensional array, which is also called a matrix.

1. Calculating the Diagonal sum of a given array

let’s say we have an array called numbers and we want to find the diagonal sum of that array.

const numbers = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

As you know that there are two diagonal in this array(numbers) :
1. Top-Left to Bottom-Right.
2. Top-Right to Bottom-Left.

So we need to calculate two different sums here. The first sum is for the diagonal line that goes from the top-left corner to the bottom-right corner, and the second sum is for the diagonal line that goes from the top-right corner to the bottom-left corner.

Top-Left to Bottom-Right

Let’s say we want to calculate the diagonal sum of the array(numbers).
This is how we will calculate the sum :

const numbers = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum = sum + numbers[i][i];
}

console.log(sum); // Output: 15

In this example, we have an array(numbers) with 3 sub-arrays, each containing 3 elements. To find the diagonal sum, we create a variable sum and set it to 0. Then, we loop through the array using a for loop and add the element at index i of each sub-array to the sum variable.

Note that the index i is used twice for each element, since we want to get elements that are on the diagonal of the array. Finally, we log the sum variable to the console, which outputs 15, the diagonal sum of the array.

Top-Right to Bottom-Left

This is how we will calculate the sum :

const numbers = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum = sum + numbers[i][numbers.length - i - 1];
}

console.log(sum); // Output: 15

To calculate the sum , we first declare a variable sum and initialize it to 0. Then, we use a for loop to iterate over each row of the array. Inside the loop, we use the loop index i to calculate the column index for the element on the diagonal line.

We do this by subtracting the current index i from the length of the array numbers.length, and then subtracting 1 to account for zero-indexing. This gives us the correct column index for the element on the diagonal line from top right to bottom left.

We then add the element at this index to the sum variable. Finally, we log the sum variable to the console, which should output 15, the sum of the elements along the diagonal line from top right to bottom left.

ALSO SEE- ARRAY.FILTER() METHOD IN JAVASCRIPT.

Leave a Comment