# Calculating quarterly and yearly average through JavaScript

Suppose, we have an array of Numbers like this −

const arr = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

We are required to write a JavaScript function that takes in one such array and chunks the array into quarterly and yearly groups intermediately.

The groups for the above array should look something like this −

const quarterly = [[1,2,2],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20]];
const yearly = [[1,2,2,4,5,6,7,8,9,10,11,12],[13,14,15,16,17,18,19,20]];

And then the function should compute the average for particular quarters and years and then return the average array.

## Example

The code for this will be −

const arr = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
const findAverages = arr => {
const quarterLength = 3, yearLength = 12;
const sumOfGroup = (arr, num) => {
return arr.reduce((acc, val, ind) => {
if (ind % num === 0){
acc.push(0);
};
acc[acc.length - 1] += val;
return acc;
}, []);
};
const quarters = sumOfGroup(arr, quarterLength);
const years = sumOfGroup(arr, yearLength);
return {
"yearlyAverage": years,
"quarterlyAverage": quarters
};
};
console.log(findAverages(arr));

## Output

The output in the console −

{
yearlyAverage: [ 77, 132 ],
quarterlyAverage: [
5, 15, 24, 33,
42, 51, 39
]
}

Updated on: 12-Oct-2020

189 Views

Get certified by completing the course