迭代数组并计算数组部分的平均值

时间:2011-07-21 15:10:02

标签: javascript arrays average

我有一个这样的数组:

["2011-06-16 16:37:20",23.2],
["2011-06-21 16:37:20",35.6],
["2011-06-26 16:37:20",41.8],
["2011-07-01 16:37:20",25],
["2011-07-06 16:37:20",22.8],
["2011-07-11 16:37:20",36.4],
["2011-07-16 16:37:20",34],
["2011-07-21 16:37:20",20]
[...]

Format: [$date,count]

现在我需要为每个数组元素添加第3个第4个值,这是之前或之后N个计数的平均值。

如果N = 3

,则示例

第3个值应该是之前3个计数值的平均值,第4个值应该是当前数组元素之后的3个计数值的平均值。 结果如下:

["2011-06-16 16:37:20",23.2, null,  34.13],
["2011-06-21 16:37:20",35.6, null,  29.86],
["2011-06-26 16:37:20",41.8, null,  28.06],
["2011-07-01 16:37:20",25,   33.53, 31.06],
["2011-07-06 16:37:20",22.8, 34.13, 30.13],
["2011-07-11 16:37:20",36.4, 29.86, null],
["2011-07-16 16:37:20",34,   28.06, null],
["2011-07-21 16:37:20",20,   31,06, null]

null值只不过是不能计算的值的占位符,因为没有足够的值来计算N个计数的平均值。 也可以为第3行而不是24.4设置所有可用计数的平均值,例如“null”(23.2 + 35.6)/ 2:

["2011-06-26 16:37:20",41.8, 24.4,  28.06],

我不知道,为此建立代码。

希望得到提示或帮助。

谢谢。

//更新:对不起,但是......请问:有人可以解释一下,为什么有2人将这个问题投票了?我不知道为什么。这不公平 - 如果我犯了错误,请跟我说说话? 对不起!

2 个答案:

答案 0 :(得分:2)

arrays = [
    ["2011-06-16 16:37:20",23.2],
["2011-06-21 16:37:20",35.6],
["2011-06-26 16:37:20",41.8],
["2011-07-01 16:37:20",25],
["2011-07-06 16:37:20",22.8],
["2011-07-11 16:37:20",36.4],
["2011-07-16 16:37:20",34],
["2011-07-21 16:37:20",20]
];
arrays.forEach(function(el,i,theArray){
    var a=null,b=null;
    if(i > 2){
        a = (theArray[i-3][1] + theArray[i-2][1] + theArray[i-1][1]) / 3;
        a = a.toPrecision(a.toString().indexOf('.') != -1 ? 2+a.toString().indexOf('.') : a.toString().length);
    }
    if(i < theArray.length - 3){
        b = (theArray[i+3][1] + theArray[i+2][1] + theArray[i+1][1]) / 3;
        b.toPrecision(b.toString().indexOf('.') != -1 ? 2+b.toString().indexOf('.') : b.toString().length);
    }
    el.push(a);
    el.push(b);
});

答案 1 :(得分:2)

使用各种高阶函数的解决方案:

var arrs = [
    ["2011-06-16 16:37:20",23.2],
    ["2011-06-21 16:37:20",35.6],
    ["2011-06-26 16:37:20",41.8],
    ["2011-07-01 16:37:20",25],
    ["2011-07-06 16:37:20",22.8],
    ["2011-07-11 16:37:20",36.4],
    ["2011-07-16 16:37:20",34],
    ["2011-07-21 16:37:20",20]];

function avg(arr) {
    return (arr.reduce(function(acc, el, i) {
        return el + acc;
    }, 0) / arr.length).toFixed(2) * 1;
}

function visit(acc, el, i, arr) {
    el.push((acc.length >= 3) ? avg(acc) : null);
    acc[i % 3] = el[1];
    return acc;
}

arrs.reduce(visit, []);
arrs.reverse().reduce(visit, []);
arrs.reverse();

结果:

[["2011-06-16 16:37:20", 23.2, null, 34.13], 
 ["2011-06-21 16:37:20", 35.6, null, 29.87], 
 ["2011-06-26 16:37:20", 41.8, null, 28.07], 
 ["2011-07-01 16:37:20", 25, 33.53, 31.07], 
 ["2011-07-06 16:37:20", 22.8, 34.13, 30.13], 
 ["2011-07-11 16:37:20", 36.4, 29.87, null], 
 ["2011-07-16 16:37:20", 34, 28.07, null], 
 ["2011-07-21 16:37:20", 20, 31.07, null]]