用 JavaScript 计算季度和年平均值
假设,我们有一个这样的数字数组 −
const arr = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
我们需要编写一个 JavaScript 函数,该函数接收其中一个数组,并将该数组分组为季度和年度组。
以上数组的组应如下所示 −
const quarterly = [[1,2,2],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20]]; const yearly = [[1,2,2,4,5,6,7,8,9,10,11,12],[13,14,15,16,17,18,19,20]];
然后,该函数应计算特定季度和年份的平均值,然后返回平均数组。
示例
其代码如下 −
const arr = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; const findAverages = arr => { const quarterLength = 3, yearLength = 12; const sumOfGroup = (arr, num) => { return arr.reduce((acc, val, ind) => { if (ind % num === 0){ acc.push(0); }; acc[acc.length - 1] += val; return acc; }, []); }; const quarters = sumOfGroup(arr, quarterLength); const years = sumOfGroup(arr, yearLength); return { "yearlyAverage": years, "quarterlyAverage": quarters }; }; console.log(findAverages(arr));
输出
控制台中的输出 −
{ yearlyAverage: [ 77, 132 ], quarterlyAverage: [ 5, 15, 24, 33, 42, 51, 39 ] }
广告