Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get average of every group of n elements in an array JavaScript
In JavaScript, calculating the average of every group of n elements in an array involves dividing the array into chunks and computing the mean for each group. This is useful for data analysis, batch processing, and statistical calculations.
Understanding the Problem
Given an array of numbers, we need to group consecutive elements into chunks of size n, then calculate the average of each group. For example, with array [1, 2, 3, 4, 5, 6] and group size 2, we get groups [1, 2], [3, 4], [5, 6] with averages [1.5, 3.5, 5.5].
Method 1: Using slice() and reduce()
This approach uses slice() to extract groups and reduce() to calculate averages:
function groupAverage(array, groupSize) {
const result = [];
for (let i = 0; i sum + num, 0) / group.length;
result.push(average);
}
return result;
}
// Example usage
const numbers = [10, 20, 30, 40, 50, 60];
const groupSize = 2;
const averages = groupAverage(numbers, groupSize);
console.log("Original array:", numbers);
console.log("Group size:", groupSize);
console.log("Group averages:", averages);
Original array: [ 10, 20, 30, 40, 50, 60 ] Group size: 2 Group averages: [ 15, 35, 55 ]
Method 2: Using Nested Loops
This method manually calculates the sum for each group:
function groupAverageNested(array, groupSize) {
const result = [];
for (let i = 0; i
Array: [ 5, 15, 25, 35, 45 ]
Groups of 3: [ 15, 40 ]
Groups of 2: [ 10, 30, 45 ]
Handling Edge Cases
Let's create a robust version that handles empty arrays and incomplete groups:
function groupAverageRobust(array, groupSize) {
// Handle edge cases
if (!array || array.length === 0 || groupSize sum + num, 0) / group.length;
result.push(Number(average.toFixed(2))); // Round to 2 decimals
}
return result;
}
// Test edge cases
console.log("Empty array:", groupAverageRobust([], 3));
console.log("Single element:", groupAverageRobust([42], 2));
console.log("Incomplete last group:", groupAverageRobust([1, 2, 3, 4, 5], 3));
Empty array: []
Single element: [ 42 ]
Incomplete last group: [ 2, 4.5 ]
Performance Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| slice() + reduce() | O(n) | O(n) | High |
| Nested Loops | O(n) | O(1) additional | Medium |
Practical Example
Here's a real-world example calculating weekly averages from daily temperatures:
// Daily temperatures for 2 weeks (14 days)
const dailyTemperatures = [72, 75, 78, 80, 77, 74, 71, 69, 73, 76, 79, 81, 78, 75];
function calculateWeeklyAverages(temperatures) {
return groupAverage(temperatures, 7).map(avg => Math.round(avg * 10) / 10);
}
const weeklyAverages = calculateWeeklyAverages(dailyTemperatures);
console.log("Daily temperatures:", dailyTemperatures);
console.log("Weekly averages:", weeklyAverages);
console.log("Week 1 average:", weeklyAverages[0] + "°F");
console.log("Week 2 average:", weeklyAverages[1] + "°F");
Daily temperatures: [ 72, 75, 78, 80, 77, 74, 71, 69, 73, 76, 79, 81, 78, 75 ] Weekly averages: [ 75.3, 75.9 ] Week 1 average: 75.3°F Week 2 average: 75.9°F
Conclusion
Calculating group averages in JavaScript can be efficiently accomplished using slice() and reduce() methods. The approach scales well with O(n) time complexity and is particularly useful for data analysis and statistical computations. Choose the method based on your specific requirements for readability and memory usage.
