Languages
[Edit]
EN

JavaScript - moving average

11 points
Created by:
Reilly-Collier
410

In this article we would like to show how to calculate moving average in JavaScript

Quick solution:

// ONLINE-RUNNER:browser;

function caculateMovingAverage(data, window) {
    var steps = data.length - window;
	var result = [ ];
    for (var i = 0; i < steps; ++i) {
        var limit = i + window;
        var sum = 0;
        for (var j = i; j < limit; ++j) {
            sum += data[j];
        }
        result.push(sum / window);
    }
  	return result;
}

// Example usage:

var data = [1, 2, 3, 4, 5, 6];
var average = caculateMovingAverage(data, 3)

for (var i = 0; i < average.length; ++i) {
	console.log(average[i]);
}

Where:

  • window means number of elements used to calculate average during one step.

Note: presented above solution has O(n^2) complexity.

Optimal solution example

Presented solution in this section has only O(n) complexity.

// ONLINE-RUNNER:browser;

function caculateMovingAverage(data, window) {
  	var result = [ ];
  	if (data.length < window) {
    	return result;
    }
    var sum = 0;
	for (var i = 0; i < window; ++i) {
      	sum += data[i];
    }
    result.push(sum / window);
  	var steps = data.length - window - 1;
    for (var i = 0; i < steps; ++i) {
      	sum -= data[i];
        sum += data[i + window];
        result.push(sum / window);
    }
  	return result;
}

// Example usage:

var data = [1, 2, 3, 4, 5, 6];
var average = caculateMovingAverage(data, 3)

for (var i = 0; i < average.length; ++i) {
	console.log(average[i]);
}

References

  1. Moving average - Wikipedia

  2. Computational complexity - Wikipedia

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join