我正在尝试根据季度系统获取总计。
[10,20,30,40,50,60,70,80,90]
- 初始数组
我正在寻找的结果是
[60, 150, 70, 80, 90]
其中Q1 = 10+20+30 = 60
Q2 = 40+50+60 = 150
只有通过 10 月份的值,Q3 才会完成。
我对自己的逻辑感到困惑
var adata = [10,20,30,40,50,60,70,80,90];
process(adata, "Sept 2014");
function process(adata, date){
var today = new Date(date) || new Date();
var aQuarter = [];
var tempQuarter = [];
var aSum = [];
//var quarter = Math.floor((today.getMonth() + 3)/3);
for(var i = 0; i<= today.getMonth(); i++) {
aQuarter.push(adata[i]);
}
tempQuarter = adata.slice();
if(tempQuarter.length > 3) {
var i = 0;
var sum = [];
while(i <= 2) {
sum[i] = aQuarter.shift();
i++;
}
console.log(sum);
aQuarter.unshift(sum);
}
if(tempQuarter.length > 6){
var i = 0;
var sum = [];
while(i+1 <= 3) {
sum[i] = aQuarter.shift();
i++;
}
aQuarter.unshift(sum);
}
console.log(aQuarter);
if(tempQuarter.length > 9){
var i = 0;
while(i+2 <= 4) {
sum[i] = aQuarter.shift();
i++;
}
}
}
最佳答案
抱歉,我稍微玩了一下 fiddle ,用这个来得到你的结果,它对你有用吗?
var adata = [10,20,30,40,50,60,70,80,90];
console.log("Sept 2014");
process(adata, "Sept 2014");
console.log("April 2014");
process(adata, "April 2014");
console.log("March 2014");
process(adata, "March 2014");
console.log("December 2014");
process(adata, "December 2014");
function process(adata, date){
var today = new Date(date) || new Date();
// reults array init
var tempArray = [];
var eachQuarterAmount = 3;
// Limit the values to January to today as defined by the date param
var aDataUpToPoint = adata.slice(0,today.getMonth() + 1);
console.log(aDataUpToPoint);
for (var i = 0; i < aDataUpToPoint.length; i+=eachQuarterAmount) {
// increment every 3 values
if (typeof aDataUpToPoint[i+eachQuarterAmount] != 'undefined') {
// If there's anything after (ie if there's Oct) then total previous values up using reduce
tempArray.push(aDataUpToPoint.slice(i,i+eachQuarterAmount).reduce(function(total, num){ return total + num },0));
} else {
// If the hunt for red October failed just tack on whatever remains
for (; i < aDataUpToPoint.length; i++) {
// uses the same loop contol variable as the parent to complete the search in both cases, picks up where it left off
tempArray.push(aDataUpToPoint[i]);
}
}
}
console.log(tempArray);
}
编辑:减少一些神奇的数字......有点。
注意:刚刚意识到您正在使用日期参数执行某些操作...所以我的 adata.length
可能应该替换为 today.getMonth()
编辑 2:将 aData 切片以在日期范围内工作,向数据集添加 +1,并从前瞻中删除 +1。
关于javascript - 按季度计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28353509/