Ad

How To Make An Average Of Nested Array

- 1 answer

I'm trying to make an average array of a bigger and dynamic array. Simpler looks like this:

const bigArr = [[[1,1,1], [2,2,2], [3,3,3]],[[3,3,3], [4,4,4], [7,7,7]]]

in the end, I'm expecting to get:

const averageArray = [[2,2,2], [3,3,3], [5,5,5]]

I know the best way is to triple loop over this array's, but I couldn't manage to get expected result.

averageArray[0][0] is an average of bigArr[0][0] and bigArr[1][0].

Ad

Answer

There are a few ways to do it (for loops, reduce, etc.) here I show an example with reduce:

const bigArr = [
              [[1,1,1], [2,2,2], [3,3,3]],
              [[3,3,3], [4,4,4], [7,7,7]],
              //[[5,5,5], [6,6,6], [11,11,11]]
            ];

const averageArray = bigArr.reduce((aggArr, arr, i) => {
  
  if (i == 0){
    return arr.map( a => a );
  }
  else {
    arr.forEach( (a, j) => {
      a.forEach( (b, k) => {
        aggArr[j][k] = ((aggArr[j][k] * i) + b) / (i + 1)
      })     
    });
  }  
  
  return aggArr;
}, []);

console.log(averageArray);

Output:

[[2,2,2], [3,3,3], [5,5,5]]

It would also work with a larger input like this:

const bigArr = [
              [[1,1,1], [2,2,2], [3,3,3]],
              [[3,3,3], [4,4,4], [7,7,7]],
              [[5,5,5], [6,6,6], [11,11,11]]
            ];

We get this output:

[[3,3,3], [4,4,4], [7,7,7]]

One final example:

It would also work with a larger input with non identical sub-arrays like this (to illustrate how the averaging is occurring):

const bigArr = [
              [[1,2,3], [1,2,3], [1,2,3]],
              [[3,4,7], [3,4,7], [3,4,7]],
              [[5,6,11], [5,6,11], [5,6,11]]
            ];

We get this output:

[[3,4,7], [3,4,7], [3,4,7]]
Ad
source: stackoverflow.com
Ad