Assume the grouping is based on continuous year instead of every 4 of the year in data list, i.e even there is no data for year 2016-2019, there is still a group for it.
function GroupedAvgData(dataList, groupSize){
//get the min(Y) for a given year
function getMinY(year, minYear){
var gap = year - minYear;
return minYear + gap - gap%groupSize;
}
//build a groups with minY as key and average as value
function buildGrouping(sortedDataList, groupSize){
var currentMin=0, currentSum=0, currentCount=0, groups={};
for(var i=0,len=sortedDataList.length; i<len;i++){
var minY = getMinY(sortedDataList[i], sortedDataList[0]);
if(currentMin != minY){
if(currentCount > 0){
groups[currentMin] = currentSum / currentCount;
}
currentCount = 1;
currentMin = minY;
currentSum = sortedDataList[i];
}else{
currentSum += sortedDataList[i];
currentCount++;
}
if( i == len - 1 && currentCount>0){
groups[currentMin] = currentSum / currentCount;
}
}
return groups;
}
this.sortedList = dataList.sort(function(a,b){return a - b;});
this.groups = buildGrouping(this.sortedList, groupSize);
this.groupSize = groupSize;
}
GroupedAvgData.prototype.getAverageForYear = function(year){
var gap = year - this.sortedList[0];
if(gap >= 0){
var minY = this.sortedList[0] + (gap-gap%this.groupSize);
if(this.groups[minY]){return this.groups[minY];}
}
return 0;
}
To use it, i.e. query the average for some year:
var Y=[2014, 2011, 2010, 2013, 2014, 2007, 2004];
var myAvg = new GroupedAvgData(Y, 4);
console.log(myAvg.getAverageForYear(2009));