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 −

 Live Demo

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 ]

Updated on: 20-Apr-2021

686 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements