
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Real-Time 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