We are required to write a JavaScript function that takes in an array of arrays of Numbers. The function should create a new array, compute the average for each subarray and push it at the corresponding indices in the new array.
Let’s say the following is our array −
const arr = [ [1], [2,3], [4,5,6,7] ];
Example
The code for this will be −
const arr = [ [1], [2,3], [4,5,6,7] ]; const average = (arr = []) => { const sum = arr.reduce((a, b) => a + b); return sum / arr.length; } const averageWithin = (arr = []) => { const res = arr.map(el => average(el)); return res; }; console.log(averageWithin(arr));
Output
And the output in the console will be −
[ 1, 2.5, 5.5 ]