Skip to content

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 ]
See also  Remove falsy values from an array in JavaScript

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.