Get average of every group of n elements in an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a Number, say n, as the second argument. The function should return an array of averages of groups of n elements.

For example: If the inputs are −

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

Then the output should be −

const output = [1.5, 3.5, 5.5];

Example

const arr = [1, 2, 3, 4, 5, 6];
const n = 2;
const groupAverage = (arr = [], n = 1) => {
   const res = [];
   for (let i = 0; i < arr.length;) {
      let sum = 0;
      for(let j = 0; j< n; j++){
         sum += +arr[i++] || 0;
      };
      res.push(sum / n);
   }
   return res
}
console.log(groupAverage(arr, n))
console.log(groupAverage(arr, 3))

Output

And the output in the console will be −

[ 1.5, 3.5, 5.5 ]
[ 2, 5 ]
raja
Published on 23-Nov-2020 07:14:18
Advertisements