假设我们有一个数字数组,如下所示:
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 ] }