Languages
[Edit]
EN

JavaScript - moving average

11 points
Created by:
Kate_C
2895

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

Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.