我有12个值的javascript数组,每个数字代表一个月。 数组已经按月排序( format ['Jan','Feb','Mar',…,'Dec'] ):
var revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0]
目标是按季度动态求和所有数字,并获得以下输出:
var revenue = [824744.78, 847140.27, 743475.59, 576379.85]
下面是我开始做的事情,但被卡在if语句中
const result = revenue.reduce((a, b, i) => {
var initialQuarterIndex = 0;
var quarterIndex = Math.floor(i/3);
if(quarterIndex === initialQuarterIndex ) {
// do something here
} else {
// do something here
}
}
答案 0 :(得分:0)
尝试一下:
let revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0];
let res = [];
for (let i = 0; i <= 3; i++) {
let quarter = revenue.splice(0, 3);//splice in quarters
let sum = quarter.reduce((v1, v2) => {
return v1 + v2;
})//calculate sum
res.push(sum);
}
console.log(res);
答案 1 :(得分:0)
您可以使用.reduce()
并仅在当前季度添加到当前值,如果在新季度(i % 3 === 0
),则可以将当前值添加为一个新的季度(即新元素),然后将其添加到以后:
const revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0];
const res = revenue.reduce((acc, n, i) => {
const curr = acc.pop();
return i && i % 3 === 0 ? [...acc, curr, n] : [...acc, curr+n]
}, [0]);
console.log(res);
答案 2 :(得分:0)
您可以使用Array#reduce,Array#fill,Array#map
完成此操作undefined
填充数组(否则.map
无效).map
遍历数组并生成索引以计算每个四分之一(= 3、6、9、12).map
通过生成的索引并计算切片的总和(= 0到2、3到5、6到8、9到11)
var revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0];
const sum = (a) => a.reduce((acc, cur)=>acc + cur);
const groupsOf = 4;
const res = (new Array(groupsOf))
.fill(undefined)
.map((_, i) => (i+1) * revenue.length / groupsOf)
.map((offset, i, arr) => sum(revenue.slice(arr[i-1] || 0, offset)));
console.log(res);
答案 3 :(得分:0)
您也可以使用for循环来实现它:
var revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0]
var result = [];
let sum = 0;
for( let i=0; i<revenue.length; i++) {
sum += revenue[i];
if( (i+1) % 3 === 0 ) {
result.push(sum);
sum = 0;
}
}
console.log(result)
答案 4 :(得分:0)
您可以使用Array.reduce
进行遍历,并使用Math.floor(i/3)
拆分季度数据。
var revenue = [207485.19, 273455.34, 343804.25, 290400.2, 330941.67, 225798.4, 295580.96, 189529.26, 258365.37, 240740.14, 202847.97, 0];
let out = revenue.reduce((acc, curr, i) => {
let index = Math.floor(i/3)
acc[index] = acc[index] + curr;
return acc
}, Array(4).fill(0));
console.log(out)
一线解决方案
let out = revenue.reduce((acc, curr, i) => (acc[Math.floor(i/3)] += curr, acc), Array(4).fill(0));