I have an array of data that is recorded by a sensor at 1 second time intervals. I am trying to calculate the max mean value for each time interval for the recorded data. If I have 2 hours worth of data, I want to calculate the max mean value for 1 second intervals, 2 second intervals, 3 second intervals etc... all the way up to 2 hours.
For example, given the following 3 values:
[8, 14, 11]
I want to return the following:
[
{
"Interval": 1,
"MeanMax": 14,
},
{
"Interval": 2,
"MeanMax": 12.5,
},
{
"Interval": 3,
"MeanMax": 11,
}
]
I have created the following function which is returning the correct value but it is very slow from a performance perspective. It takes approx 30 seconds to calculate the output for a 2 hour block of data. It is calculating all possible mean values for the given interval and then returning the largest.
let sampleData = Array.from({length: 20}, () => Math.floor(Math.random() * 20));
console.log("SampleData: " + sampleData)
let meanMaxByTimeFrame = [];
for(var intervalInSeconds = 1; intervalInSeconds <= sampleData.length; intervalInSeconds++){
let allAveragesForCurrentInterval = [];
for(var sampleDataIndex = 0; sampleDataIndex < sampleData.length; sampleDataIndex++){
if((sampleDataIndex + intervalInSeconds) > sampleData.length){
break;
}
let sum = sampleData.slice(sampleDataIndex, sampleDataIndex + intervalInSeconds).reduce((a, b) => a + b, 0);
let avg = sum/intervalInSeconds;
allAveragesForCurrentInterval.push(avg);
}
meanMaxByTimeFrame.push({'Interval': intervalInSeconds, 'MeanMax': Math.max.apply(Math, allAveragesForCurrentInterval)});
}
console.log(meanMaxByTimeFrame)
Any help would be much appreciated