Find average of each array within an array JavaScript

We are required to write a function getAverage() that accepts an array of arrays of numbers and we are required to return a new array of numbers that contains the average of corresponding subarrays.

Let's write the code for this. We will map over the original array, reducing the subarray to their averages like this ?

Example

const arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]];
const secondArr = [[545,65,5,7], [0,0,0,0], []];
const getAverage = (arr) => {
    const averageArray = arr.map(sub => {
        const { length } = sub;
        return sub.reduce((acc, val) => acc + (val/length), 0);
    });
    return averageArray;
}
console.log(getAverage(arr));
console.log(getAverage(secondArr));

Output

The output in the console will be ?

[ 87.375, 2.5, 5.5 ]
[ 155.5, 0, 0 ]

How It Works

The function uses map() to iterate through each subarray and reduce() to calculate the sum. Instead of dividing the total sum by length at the end, it divides each value by the length during the reduction process, which gives the same result.

Alternative Approach

Here's a more straightforward approach that calculates the sum first, then divides by length:

const getAverageSimple = (arr) => {
    return arr.map(sub => {
        if (sub.length === 0) return 0;
        const sum = sub.reduce((acc, val) => acc + val, 0);
        return sum / sub.length;
    });
}

const testArr = [[10, 20, 30], [5, 15], []];
console.log(getAverageSimple(testArr));
[ 20, 10, 0 ]

Conclusion

Both approaches effectively calculate averages of nested arrays using map() and reduce(). The second approach is more readable as it clearly separates sum calculation from division.

Updated on: 2026-03-15T23:18:59+05:30

257 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements