# Realtime moving average of an array of numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

## 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 ]