Calculating average of a sliding window in JavaScript

We are required to write a JavaScript function that takes in an array of integers, arr, as the first argument and a number, num (num < length of arr) as the second argument. The function should construct and return a new array that contains the average of all possible num contiguous numbers of the array.

For example −

If the input array and the number are −

const arr = [1, 2, 3, 4, 5];
const num = 2;

Then the output should be −

const output = [1.5, 2.5, 3.5, 4.5];

because the possible continuous windows of size two are (1, 2), (2, 3), (3, 4) and (4, 5)

Sliding Window Approach

This problem uses the sliding window technique - an efficient method where we maintain a fixed-size window and slide it across the array. Instead of recalculating the entire sum for each window, we add the new element and remove the old one.

Sliding Window (size = 2) 1 2 3 4 5 Window 1: (1+2)/2 = 1.5 Window 2: (2+3)/2 = 2.5

Example

The code for this will be −

const arr = [1, 2, 3, 4, 5];
const num = 2;

const findContinuousAverage = (arr = [], num = 1) => {
    if(num > arr.length){
        return [];
    };
    
    const res = [];
    let sum = 0;
    let left = 0, right = 0;
    
    // Calculate sum of first window
    for(; right < num; right++){
        sum += arr[right];
    };
    res.push(sum / num);
    
    // Slide the window
    for(; right < arr.length; right++, left++){
        sum -= arr[left];   // Remove leftmost element
        sum += arr[right];  // Add new rightmost element
        res.push(sum / num);
    };
    
    return res;
};

console.log(findContinuousAverage(arr, num));
console.log(findContinuousAverage(arr));

Output

And the output in the console will be −

[ 1.5, 2.5, 3.5, 4.5 ]
[ 1, 2, 3, 4, 5 ]

How It Works

The algorithm works in two phases:

  1. Initialize first window: Calculate the sum of the first 'num' elements
  2. Slide the window: For each subsequent position, remove the leftmost element and add the new rightmost element

This approach has O(n) time complexity instead of O(n*k) for the naive approach, making it much more efficient for large arrays.

Alternative Simple Approach

const simpleAverage = (arr, windowSize) => {
    const result = [];
    
    for(let i = 0; i <= arr.length - windowSize; i++) {
        let sum = 0;
        for(let j = i; j < i + windowSize; j++) {
            sum += arr[j];
        }
        result.push(sum / windowSize);
    }
    
    return result;
};

console.log(simpleAverage([1, 2, 3, 4, 5], 2));
console.log(simpleAverage([1, 2, 3, 4, 5, 6], 3));
[ 1.5, 2.5, 3.5, 4.5 ]
[ 2, 3, 4, 5 ]

Conclusion

The sliding window technique provides an efficient solution for calculating moving averages. The optimized approach maintains O(n) complexity by reusing calculations, making it ideal for large datasets or real-time applications.

Updated on: 2026-03-15T23:19:00+05:30

688 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements