二维数组的总和

时间:2013-02-26 06:52:32

标签: javascript

array[time, value];我需要来自这个二维数组的总值/总和值吗?

var array =[ 
    [1361824790262, 90.48603343963623],
    [1361828390262, 500.18687307834625],
    [1361831990262, 296.05108177661896], 
    [1361835590262, 423.1198309659958], 
    [1361839190262, 11.86623752117157], 
    [1361842790262, 296.38282561302185], 
    [1361846390262, 424.31847417354584], 
    [1361849990262, 100.07041704654694], 
    [1361853590262, 434.8605388402939],
    [1361857190262, 434.8220944404602],
    [1361860790262, 183.61854946613312]
];
var sum = 0;
//console.log(array.length);
for (var i = 0; i < array.length; i++) {
    //console.log(array[i]);
    for (var j = 0; j < array[i].length; j++) {
        console.log(array[j][i]);
        sum += array[j][i];
    }
}
console.log(sum);

Link for JsFiddle

4 个答案:

答案 0 :(得分:9)

你的问题标题意味着你要总结一个二维数组 - 这是你将如何做到这一点:

array.reduce(function(a,b) { return a.concat(b) }) // flatten array
     .reduce(function(a,b) { return a + b });      // sum

如您在编辑中明确指出的那样,只对值部分求和更加容易:

array.map(function(v) { return v[1] })         // second value of each
     .reduce(function(a,b) { return a + b });  // sum

答案 1 :(得分:1)

不需要两个循环。这循环遍历数组并为您提供每个时间/值对。如果每个时间 - 值对,只需将第一个索引(第二个项目)相加。

var sum = 0;
for(var i=0;i<array.length;i++){
    console.log(array[i]);
    sum += array[i][1];
}
console.log(sum);

输出:

[1361824790262, 90.48603343963623] 
[1361828390262, 500.18687307834625]
[1361831990262, 296.05108177661896]
[1361835590262, 423.1198309659958] 
[1361839190262, 11.86623752117157] 
[1361842790262, 296.38282561302185]
[1361846390262, 424.31847417354584]
[1361849990262, 100.07041704654694]
[1361853590262, 434.8605388402939] 
[1361857190262, 434.8220944404602] 
[1361860790262, 183.61854946613312]
3195.7829563617706 

答案 2 :(得分:0)

    Sum_of_2d_array(arr)
    {
        int sum_time =0;
        int sum_value=0;

        for(i=0;i<arr.length;i++)
        {
            sum_time = sum_time + arr[i,0];
        }
        print(sum_time);

        for(i=0;i<arr.length;i++)
        {
            sum_value = sum_value + arr[i,1];
        }
        print(sum_value);
    }

    If I understood your question correctly. I think this is what you want.

答案 3 :(得分:0)

var arr = [[1361824790262, 90.48603343963623],
[1361828390262, 500.18687307834625],
[1361831990262, 296.05108177661896], 
[1361835590262, 423.1198309659958], 
[1361839190262, 11.86623752117157], 
[1361842790262, 296.38282561302185], 
[1361846390262, 424.31847417354584], 
[1361849990262, 100.07041704654694], 
[1361853590262, 434.8605388402939],
[1361857190262, 434.8220944404602],
[1361860790262, 183.61854946613312]];

var sum = 0;
 for(var i=0;i<arr.length;i++){
    for(var j=0;j<arr[i].length;j++){
        sum += arr[i][j];
    }
}
console.log(sum);

这是获得总数的解决方案。我测试过了。