-3

In JavaScript I generate an x number of arrays, all consisting 57 numbers. I want to calculate the average of each single number in the array as a result in one array with the averages i.e.:

array1[0] + array2[0] + array3[0] .... / number of arrays = average of [0]

array1[1] + array2[1] + array3[1] .... / number of arrays = average of [1]

array1[2] + array2[2] + array3[2] .... / number of arrays = average of [2]

This is an example of a generated array of arrays:

(5) [Array(57), Array(57), Array(57), Array(57), Array(57)]
0
: 
(57) [4, 3, 3, 4, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 4, 3, 5, 5, 4, 4, 4, 4, 3, 4, 3, 4, 3, 4, 4, 4, 4, 3, 4, 3, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 3, 5, 3, 5]
1
: 
(57) [1, 3, 1, 2, 1, 3, 2, 2, 3, 1, 2, 1, 3, 2, 3, 1, 4, 4, 4, 4, 4, 3, 1, 1, 4, 3, 3, 2, 2, 2, 4, 3, 3, 3, 3, 2, 3, 3, 3, 1, 2, 1, 1, 2, 2, 4, 1, 4, 1, 1, 3, 4, 3, 2, 1, 2, 4]
2
: 
(57) [1, 3, 2, 4, 4, 4, 3, 4, 5, 4, 2, 4, 2, 3, 3, 4, 2, 1, 1, 2, 2, 1, 2, 3, 4, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 4, 4, 1, 2, 3, 2, 2, 4, 3, 4, 2, 4, 4, 2, 2, 1, 2, 3, 1, 2, 1, 1]
3
: 
(57) [2, 4, 4, 3, 2, 3, 1, 4, 3, 3, 1, 2, 1, 1, 3, 4, 4, 2, 3, 2, 2, 1, 2, 2, 4, 1, 2, 1, 1, 4, 2, 3, 3, 3, 1, 4, 1, 4, 1, 4, 4, 4, 1, 1, 3, 3, 3, 4, 1, 3, 2, 1, 4, 1, 1, 2, 4]
4
: 
(57) [1, 1, 3, 1, 1, 2, 4, 4, 5, 1, 2, 1, 2, 2, 3, 4, 4, 2, 1, 3, 1, 2, 4, 3, 4, 4, 4, 4, 1, 3, 1, 2, 2, 4, 1, 4, 1, 3, 3, 4, 1, 3, 4, 2, 4, 1, 4, 3, 4, 1, 2, 4, 4, 1, 1, 4, 4]
length
: 
5
[[Prototype]]
: 
Array(0)

Can anyone give me an example whereby I can build this solution properly?

Wolk9
  • 69
  • 8
  • `allArrays.reduce((a, b) => a.concat(b), []).reduce((a, b) => a + b, 0) / allArrays.reduce((a, b) => a + b.length, 0);` – code Oct 15 '22 at 19:22

1 Answers1

-1

assuming rawArrays is your generated array of arrays of numbers.

const amountOfArrays = 2, amountOfNumbersInArray = 3;
const rawArrays = [
  [1, 2, 3],
  [4, 5, 6],
];

const averagesOnArrayIndex = rawArrays[0].map((_, id) => {
  const sumOfElementsOnThisId = rawArrays.map((array) => array[id]).reduce((acc, cur) => acc += cur, 0);
  const averageOnThisId = sumOfElementsOnThisId / amountOfArrays;
  return averageOnThisId;
});
rickshinova
  • 109
  • 6