How to find the sum of each row and each column of a matrix (2D array) in Node.js

1 Answer

0 votes
const arr = [
    [1, 2, 3, 5],
    [4, 5, 6, 5],
    [7, 8, 9, 5]
];
  
const rows = arr.length;
const cols = arr[0].length;
  
for (let i = 0; i < rows; i++) {
    let sumRow = 0
    for (let j = 0; j < cols; j++) {
        sumRow = sumRow + arr[i][j];  
    }
    console.log("Sum of row:" + i + " = " + sumRow); 
}
 
for (let i = 0; i < cols; i++) {
    let sumCol = 0
    for (let j = 0; j < rows; j++) {
        sumCol = sumCol + arr[j][i];  
    }
    console.log("Sum of col:" + i + " = " + sumCol); 
}
 
 
 
               
      
/*
run:
      
Sum of row:0 = 11
Sum of row:1 = 20
Sum of row:2 = 29
Sum of col:0 = 12
Sum of col:1 = 15
Sum of col:2 = 18
Sum of col:3 = 15
     
*/

 



answered Nov 20, 2022 by avibootz
...