Find Average of Each Array Within an Array in 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 ]
Updated on: 2020-08-20T06:19:40+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close