# Calculating the average for each subarray separately and then return the sum of all the averages in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of arrays of Integers like this −

const arr = [
[1, 2, 3],
[4, 5, 6]
];

We are required to write a JavaScript function that takes in one such array of arrays. The function should calculate the average for each subarray separately and then return the sum of all the averages.

Therefore, for the above array the output should be −

2 + 5 = 7

## Example

The code for this will be −

const arr = [
[1, 2, 3],
[4, 5, 6]
];
const sumAverage = (arr = []) => {
const average = arr.reduce((acc, val) => {
const total = val.reduce((total, num) => total += num, 0);
return acc += total / val.length;
}, 0);
return Math.round(average);
};
console.log(sumAverage(arr));

## Output

And the output in the console will be −

7
Updated on 23-Nov-2020 07:59:20