Javascript Multidimensional Array: Add Values

2020-07-30 00:35发布

问题:

So I have a multidimensional array like:

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

I would like to add the similar values up. So in the end I just have:

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

Can you give me an example of how to accomplish this? Either with Javascript and/or jQuery

Thanks!

回答1:

I am not sure if you want an array or object. If object, stop it is 1st pass and tmp in below code should return you the object as 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:

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/

you can use values to create the query string



回答3:

Check this code:

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/



回答4:

Underscore solution:

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

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

A little dirtier in jQuery

sums = {}

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

Edit: add jQuery version