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

In the given problem, we have to find out the average of every group of n elements in the array. If there are m elements in the array, then calculate the average of every group and show the result in array form.

## Understanding the Problem

Suppose we have 6 elements in the array and make a group of 2 elements. Now calculate the average of every group individually. Now that we have their average values, we can combine them into a single array.

To implement this problem we have used reduce(), push(), and slice(). These are the predefined methods in javascript.

The reduce() function will run a reducer function on every element of the array and give a single output value. The syntax of the reduce() function is:

 array.reduce(callbackFunction(currentValue, currentIndex), initialValue)


The push() function is used to push all the elements into the array. It adds a new item to the array at the last index. It also changes the size of the array. The syntax for "push()" is as follows:

Input

colors = ["Red", "Blue", "Black"];
colors.push("Pink","Grey");


Output

[ 'Red', 'Blue', 'Black', 'Pink', 'Grey' ]


The slice() function returns selected items from an array as a new array by slicing them. The mechanism of this function is to select the element from a mentioned starting point to an ending point. The property of this function, it does not change the actual array. The syntax is as follows:

Input

colors = ["Red", "Blue", "Black", "Pink", "Grey"];
color = colors.slice(1,3);


Output

[ 'Blue', 'Black' ]


## Algorithm - Using slice, reduce and push functions

Step 1: To solve this problem, declare a function with the name groupAverage that takes in an integer array as an input.

Step 2: After declaring the function we need to declare an array to store the elements and name it result with 0 value (Initialize empty).

Step 3: Starting with the for loop one can traverse through each and every character of the integer elements till array.length.

Step 4: Now this is the main step in which we will create a group of elements and assign them to the batch variable.

Step 5: This step will determine the average value of every group we have created. So for doing this we will add up the components of each group, calculate their average, and give the avg variable a value.

Step 6: Now in this path the calculated average values will be added or pushed in the result array.

Step 7: Give the results after calculating the average for every group. After getting the average values we need to push them in a new array. So the outcome will be the array of arrays.

### Example

//Define a function to calculate average
function groupAverage (a, n) {
var result = [];

for (let i = 0; i < a.length; i =i+n) {
var batch = a.slice(i, i + n);
var avg = batch.reduce((sum, b) => sum + b, 0) / batch.length;
result.push(avg);
}

return result;
}
//Define array and number to calculate average of groups
var arr = [11, 21, 31, 41, 51, 61, 71, 81, 91];
var num = 3;

// Calling the function and store it in result
var output = groupAverage(arr, num);
console.log("Average of every group of n elements in an array")
console.log(output);


### Output

Average of every group of n elements in an array
[ 21, 51, 81 ]


In the above code we have defined a function named groupAverage() that takes two parameters: an array āaā and a number ānā. Use a for loop to iterate over the elements of the array, increase by n at each step.

Inside the loop, slice the array from the current index to n elements ahead, and add the result to a variable called group. Calculate the average of the group by calling the javascript function reduce() on the group and divide by its length, and assign the result to a variable called avg. Now push the avg value to the result array. Then return and show the result from the function.

## Algorithm - Using two for loops

Step 1: At first step, define the array with some values in it.

Step 2: Create a function and give the name groupAvg(). The function is taking two parameters array and num. Where num is the number of elements in a single group and array is the variable we have defined in the first step.

Step 3: After the second step define an array to store the result.

Step 4: Define a for loop to run until the length of the array. Also initialize a sum variable with 0 initial value.

Step 5: At this step, declare one more for loop which will iterate the group elements.

Step 6: Determine whether the value is a number in this phase. Set the default value to 0 in the absence of a numeric value.

Step 7: In the result array, add the average values of the various groups.

Step 8: As a last step, print the output and return the value of the result.

## Example

//Declare an array with name array
const array = [2, 1, 5, 4, 1, 3, 6, 7, 9];

//Function to calculate Average of groups
function groupAvg(array, num) {
var result = [];
for (let i = 0; i < array.length;) {
var sum = 0;
for(let j = 0; j< num; j++){
sum += +array[i++] || 0
}
result.push(sum/num);
}
return result
}

console.log("Group average for 3 and 2 items respectively: ")
console.log(groupAvg(array, 3))
console.log(groupAvg(array, 2))


### Output

Group average for 3 and 2 items respectively:
[ 2.666666666665, 2.666666666666665, 7.33333333333333 ]
[ 1.5, 4.5, 2, 6.5, 4.5 ]


## Complexity

As we can see from the implementations above, for loops were employed to achieve the desired outcome. Now we have discovered that groupCount() only functions for the number of items that are present in the object. The time complexity is then O (n). where n represents the size of the incoming data. Also, because the total function keeps one count value per stack in the group object, the program requires the same amount of memory, O(n).

## Conclusion

This algorithm gives basic ideas about the usage of slice(), reduce() and push() functions. And the time complexity for this algorithm is O(N). With the help of this problem we will have an idea about slicing and calculating the average of grouping elements in the array. This is how we can solve the given problem. It will improve logical thinking and coding skills with less time complexity and space complexity.

Updated on: 18-Aug-2023

779 Views