Search code examples
javascriptarraysmatrix

Find the average per index in a matrix


I'm looking to get the average of each index in a matrix row in JS

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Then returning a list with the average of each row index : [4, 5, 6]

Would I create a loop, save each index to a list, add them up, and divide them, then form new list with averages? I feel like there is probably a simpler way.


Solution

  • Easy peasy here how you can achieve the average via given matrix :

    const matrix = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ];
    const averages = [];
    for (let col = 0; col < matrix[0].length; col++) { // loop to iterate over columns
      let sum = 0;
      for (let row = 0; row < matrix.length; row++) { // loop to iterate over rows
        sum += matrix[row][col]; // calculate accumulated sum
      }
      const average = sum / matrix.length; // get sum divided by matrix length
      averages.push(average);
    }
    
    console.log(JSON.stringify(averages));