Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Realtime moving average of an array of numbers in JavaScript
A moving average calculates the average of elements from the start of an array up to each position. For each element at index i, we compute the average of elements from index 0 to i.
Problem
We need to write a JavaScript function that takes an array of numbers and returns a new array containing the cumulative moving average at each position.
Input: [1, 2, 3, 4, 5] Output: [1, 1.5, 2, 2.5, 3]
The first element is the average of just the first element (1/1 = 1). The second element is the average of the first two elements ((1+2)/2 = 1.5), and so on.
Solution
We'll iterate through the array, maintaining a running sum and count to calculate the average efficiently:
const arr = [1, 2, 3, 4, 5];
const movingAverage = (arr = []) => {
const result = [];
let sum = 0;
for (let i = 0; i
[ 1, 1.5, 2, 2.5, 3 ]
[ 10, 15, 20, 25 ]
[ 5, 10, 15 ]
How It Works
The algorithm maintains a running sum and divides by the current position plus one (since arrays are zero-indexed). This approach has O(n) time complexity and O(n) space complexity.
Alternative Implementation with Reduce
Here's a functional programming approach using reduce:
const movingAverageReduce = (arr = []) => {
return arr.reduce((result, current, index) => {
const sum = arr.slice(0, index + 1).reduce((a, b) => a + b, 0);
result.push(sum / (index + 1));
return result;
}, []);
};
const testArray = [2, 4, 6, 8, 10];
console.log(movingAverageReduce(testArray));
[ 2, 3, 4, 5, 6 ]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| For Loop | O(n) | O(n) | High |
| Reduce with Slice | O(n²) | O(n) | Medium |
Conclusion
The for loop approach is more efficient for calculating moving averages, maintaining O(n) time complexity. Use this method for performance-critical applications or large datasets.
