- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Realtime moving average of an array of numbers in JavaScript
Problem
We are required to write a JavaScript function that takes in an array. Our function should construct a new array that stores the moving average of the elements of the input array. For instance −
[1, 2, 3, 4, 5] → [1, 1.5, 3, 5, 7.5]
First element is the average of the first element, the second element is the average of the first 2 elements, the third is the average of the first 3 elements and so on.
Example
Following is the code −
const arr = [1, 2, 3, 4, 5]; const movingAverage = (arr = []) => { const res = []; let sum = 0; let count = 0; for(let i = 0; i < arr.length; i++){ const el = arr[i]; sum += el; count++; const curr = sum / count; res[i] = curr; }; return res; }; console.log(movingAverage(arr));
Output
Following is the console output −
[ 1, 1.5, 2, 2.5, 3 ]
Advertisements