1

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

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

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

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

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

谢谢!

4

4 回答 4

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);​

演示:http: //jsfiddle.net/Ta97E/2/

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

于 2012-05-07T19:36:06.670 回答
3

我不确定你是否想要一个数组或对象。如果对象,停止它是第一次通过,tmp在下面的代码中应该将对象返回为Object { venue=18, inning=38, hithard=4}.

演示

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]]     
于 2012-05-07T19:43:07.423 回答
2

检查此代码:

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

console.log(final);​

演示:http: //jsfiddle.net/UVJEb/

于 2012-05-07T19:43:12.240 回答
2

下划线解决方案:

 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 版本

于 2012-05-07T19:44:38.013 回答