在JavaScript数组中求和总计

时间:2014-02-06 16:21:33

标签: javascript jquery arrays

我有一个动态JavaScript数组正在我的页面上创建(这些数字都不会相同,有很多变化),例如:

 myArray[ 1 ] = [295518, 2];
 myArray[ 2 ] = [123518, 123];
 myArray[ 3 ] = [295518, 43];
 myArray[ 4 ] = [295518, 65];
 myArray[ 5 ] = [234518, 3];
 myArray[ 6 ] = [567518, 56];

此数组的说明:

                [id number, quantity]
 myArray[ 1 ] = [295518,    2];

我需要将所有类似的id数组元素组合在一起并对它们的值求和。

 For instance: 295518 would add 2 + 43 + 65 = 110

然后我需要它来更新页面上的id值:

 $("#295518").text(110); 

所以我想的是这个,但我不确定如何用JavaScript编写它:

 [start JavaScript loop]
      [grab distinct ids]
           [start id loop]
                [grab all values based on id]
                [sum their qty values]
                [set the id element on the page with the sum value]
                     [example: $("#295518").text(110); ]
           [end id loop]
 [/end JavaScript loop]

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题......

var myArray = [];
myArray.push([295518, 2]);
myArray.push([123518, 123]);
myArray.push([295518, 43]);
myArray.push([295518, 65]);
myArray.push([234518, 3]);
myArray.push([567518, 56]);

var result = {};

$(myArray).each(function() {
    var key = this[0];
    var value = this[1];
    if (result[key]) {
        result[key] += value;
    } else {
        result[key] = value;
    }
});

console.log(result);

<强> Here's a working example...

仅仅为了完整性,没有jQuery就是一样的东西(如果你不需要它的话)......

var myArray = [];
myArray.push([295518, 2]);
myArray.push([123518, 123]);
myArray.push([295518, 43]);
myArray.push([295518, 65]);
myArray.push([234518, 3]);
myArray.push([567518, 56]);

var result = {};

for (i in myArray) {
    var key = myArray[i][0];
    var value = myArray[i][1];
    if (result[key]) {
        result[key] += value;
    } else {
        result[key] = value;
    }
}

console.log(result);

答案 1 :(得分:0)

假设myArray始终包含length为2的数组,您可以执行以下操作:

var myArray = [
    [295518, 2],
    [123518, 123],
    [295518, 43],
    [295518, 65],
    [234518, 3],
    [567518, 56]
];
var allSums = {};

$.each(myArray, function( i, pair ) {
    if( allSums[pair[0]] ) {
        allSums[pair[0]] += pair[1];
    }
    else {
        allSums[pair[0]] = pair[1];
    }
});

DEMO