Every minute, my array updates. To show the daily average of each hour, I need to calculate the average for every 60 elements.
The latest minute gets added at the end of the array.
// Retrieving the last elements from the array
var hours = (this.today.getHours() + 1) * 60
var data = Array.from(this.temps.data)
let lastData = data.slice(Math.max(data.length - hours))
let newData: any
// Calculating the hourly averages
for (let i = 0; i < minutes; i++) {
var cut = i * 60
for (let j = cut; j < (cut + 60); j++) {
newData = newData + lastData[j];
let test = newData/60
console.log(test);
}
}
I'm unsure how to create an array from the last 60 elements. My aim is to have an array like:
avgHour[20,22,30,27,]
The array I currently have is updated every minute, so I require the average of every 60 elements to represent an hour.
This array looks something like:
data[25,33,22,33]
Given that it represents every minute over a week, the array is quite lengthy.
This Solution Worked for Me
var arrays = [], size = 60;
while (arr.length > 0){
arrays.push(arr.splice(0, size));
}
for (let i = 0; i < (arrays.length - 1); i++) {
var sum = 0
for (let b = 0; b < 60; b++) {
sum += arrays[i][b]
}
let avg = sum/60
arr2.push(avg)
}
This code essentially divides the array into smaller chunks of 60 elements each. This allows me to compute the average for each set of 60 elements.
Grateful for the assistance!