- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 ] }

- Related Articles
- Calculating excluded average - JavaScript
- Calculating average of an array in JavaScript
- Calculating average of a sliding window in JavaScript
- Calculating the average for each subarray separately and then return the sum of all the averages in JavaScript
- Calculating average value per document with sort in MongoDB?
- Calculating factorial by recursion in JavaScript
- Calculating resistance of n devices - JavaScript
- Calculating Josephus Permutations efficiently in JavaScript
- Calculating median of an array JavaScript
- Calculating least common of a range JavaScript
- Calculating median of an array in JavaScript
- Euclidean Algorithm for calculating GCD in JavaScript
- Calculating and adding the parity bit to a binary using JavaScript
- Find the compound interest on Rs. 6,000 for 1 year at the rate of 4% per annum if the interest is a) Compounded half-yearly b) compounded quarterly
- Calculating the LCM of multiple numbers in JavaScript

Advertisements