Calculate moving average of an array of numbers in JavaScript
Moving average is the average of the current element and the previous elements in an array. We can use the following code snippet to achieve it.
Advertisements
const numbers = [10, 20, 30, 40, 50]; const getMovingAverage = (numbers = []) => { const result = []; let sum = 0; let count = 0; for(let i = 0; i < numbers.length; i++){ const num = numbers[i]; sum += num; count++; const curr = sum / count; result[i] = curr; }; return result; }; console.log(getMovingAverage(numbers)); //[ 10,15,20,25,30 ]