Javascript多维数组:添加值

时间:2012-05-07 19:33:12

标签: javascript jquery multidimensional-array add

所以我有一个多维数组,如:

myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]]

我想添加类似的值。所以最后我才有:

"venue" = 18, "inning" = 38, and "hithard" = 4.

你能举个例子说明如何做到这一点吗?使用Javascript和/或jQuery

谢谢!

4 个答案:

答案 0 :(得分:3)

myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]];
values = {};
for (i=0;i<myArr.length;i++){
   if ("undefined" == typeof values[myArr[i][0]]) {values[myArr[i][0]] = 0;}
   values[myArr[i][0]] += myArr[i][1];
}
arr = [];
query_string = "";
for (i in values) {
    // if you want it in an array:
    arr.push('"' + i + '" = ' + values[i]);
    query_string += (query_string.length ? "&" : "") + i + "=" + values[i];
}
​console.log(arr);​

DEMO:http://jsfiddle.net/Ta97E/2/

您可以使用值来创建查询字符串

答案 1 :(得分:3)

我不确定您是否需要数组或对象。如果是对象,请将其停止为第一遍,并且下面的代码中的tmp应该将对象作为Object { venue=18, inning=38, hithard=4}返回给您。

DEMO

var tmp = {}, keys;
for (var i = 0; i < myArr.length; i++) {
    keys = myArr[i][0];
    tmp[keys] = (tmp.hasOwnProperty(keys))? 
              (tmp[keys] + myArr[i][1]):myArr[i][1];
} //tmp - will return you a Object { venue=18, inning=38, hithard=4}

var output = [];
for (keys in tmp) {
    output.push([keys, tmp[keys]]);
} //output will return you an array as [["venue", 18],["inning", 38],["hithard", 4]]     

答案 2 :(得分:2)

检查此代码:

var final = {};
for (var i in myArr) {
    var item = myArr[i];
    final[item[0]] = (final[item[0]] || 0) + item[1];
}

console.log(final);​

DEMO: http://jsfiddle.net/UVJEb/

答案 3 :(得分:2)

Underscore解决方案:

 sums = _.reduce(myArr, function (obj, item) { 
    obj[item[0]] = (obj[item[0]] || 0) + item[1]; 
    return obj; 
 }, {});

 // sums = {"venue":18,"inning":38,"hithard":4}

jQuery中的一点点肮脏

sums = {}

$.each(myArr, function (i, value) {
    sums[value[0]] = (sums[value[0]] || 0) + value[1];
});

编辑:添加jQuery版本