skip to Main Content

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.

2

Answers


  1. 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));
    Login or Signup to reply.
  2. You can use Array#reduce and Array#map methods as follows:

    const 
          input = [
            [1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]
          ],
          
          output = input.reduce(
              (acc,cur,i,a) => acc.map(
                  (x,j) => x + cur[j]/a.length
              ), 
              Array(input.length).fill(0)
          );
    
    console.log( output );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search