
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 ]
- Related Articles
- Calculating average of an array in JavaScript
- Find average of each array within an array in JavaScript
- Find average of each array within an array JavaScript
- Splitting array of numbers into two arrays with same average in JavaScript
- Get average of every group of n elements in an array JavaScript
- Equal partition of an array of numbers - JavaScript
- Smallest Common Multiple of an array of numbers in JavaScript
- Product of all other numbers an array in JavaScript
- Sum of all prime numbers in an array - JavaScript
- Calculating variance for an array of numbers in JavaScript
- Average of array excluding min max JavaScript
- Finding missing element in an array of numbers in JavaScript
- Performing power operations on an array of numbers in JavaScript
- Average numbers in array in C Programming
- Squared and square rooted sum of numbers of an array in JavaScript

Advertisements