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)

Example

The code for this will be −

 Live Demo

const arr = [1, 2, 3, 4, 5];
const num = 2;
const findContiniousAverage = (arr = [], num = 1) => {
   if(num > arr.length){
      return [];
   };
   const res = [];
   let sum = 0;
   let left = 0, right = 0;
   for(; right < num; right++){
      sum += arr[right];
   };
   res.push(sum / num);
   for(; right < arr.length; right++, left++){
      sum -= arr[left];
      sum += arr[right];
      res.push(sum / num);
   };
   return res;
};
console.log(findContiniousAverage(arr, num));
console.log(findContiniousAverage(arr));

Output

And the output in the console will be −

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

Updated on: 26-Feb-2021

375 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements