通过javascript计算季度和年度平均值

时间:2017-08-15 14:37:58

标签: javascript arrays

我有一个数组:

const test = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

我想将数组的元素分组为大小为3(四分之一)和大小为12(年)的块:

const quarters = [[1,2,2],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18],[19,20]];
const years = [[1,2,2,4,5,6,7,8,9,10,11,12],[13,14,15,16,17,18,19,20]];

我还想计算每个块的总和:

const quarterSums = [5,15,24,33,42,51,39];
const yearSums = [77,132];

我该怎么做?

3 个答案:

答案 0 :(得分:2)

使用按组大小递增的循环,并使用.slice()

编辑:您添加的信息不在原始问题中。由于您似乎想要每个季度/年的总和,请将此.reduce((s,n)=>s+n, 0)添加到每个子集。这样可以更好地使用.reduce()

const test = [1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

console.log(getGroups(test, 3)); // quarters
console.log(getGroups(test, 12)); // years

function getGroups(a, s) {
  for (var i = 0, r = []; i < a.length; i += s) {
    r.push(a.slice(i, i + s).reduce((s,n)=>s + n, 0));
  }
  return r;
}

使用.reduce()等访问每个元素的内容会使这种情况更加复杂。传统的for循环提供了定义循环应该如何递增的好处。

如果你更喜欢更多的函数方式,我仍然不会使用.reduce(),而是会推出自己的尾递归。

const test = [1, 2, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

console.log(getGroups(test, 3)); // quarters
console.log(getGroups(test, 12)); // years

function getGroups(a, s) {
  return function p(a, s, r) {
    return !a.length ? r : r.concat(a.slice(0, s).reduce((s,n)=>s + n, 0),
                                    p(a.slice(s), s, r));
  }(a, s, []);
}

答案 1 :(得分:1)

您可以使用带有对象的Array#forEach作为临时变量来收集值。然后计算平均值。

var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
    temp = { quarter: { avg: [], items: 3, sum: 0 }, year: { avg: [], items: 12, sum: 0 } }
  
values.forEach(function (v, i) {
    Object.keys(temp).forEach(function (k) {
        temp[k].sum += v;
        if (i && (i + 1) % temp[k].items === 0) {
            temp[k].avg.push(temp[k].sum / temp[k].items);
            temp[k].sum = 0;
        }
    });
});

console.log(temp.quarter.avg);
console.log(temp.year.avg);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

如果要将元素分组为大小为n的块,则:

const groupInto = (n, xs) => xs.reduce((xss, x, i) => {
    if (i % n === 0) xss.push([]); // create a new group
    xss[xss.length - 1].push(x);   // push in last group
    return xss;
}, []);

const xs = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

const quarters = groupInto(3,  xs);
const years    = groupInto(12, xs);

console.log(JSON.stringify(quarters));
console.log(JSON.stringify(years));

另一方面,如果你想找到这些块的总和:

const sumInto = (n, xs) => xs.reduce((ys, x, i) => {
    if (i % n === 0) ys.push(0);
    ys[ys.length - 1] += x;
    return ys;
}, []);

const xs = [1,2,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

const quarters = sumInto(3,  xs);
const years    = sumInto(12, xs);

console.log(JSON.stringify(quarters));
console.log(JSON.stringify(years));

希望有所帮助。