Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

jquery array group by

I have array like this

abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]]

how can I group and sum values by A, B, C...

$.each(abcArr , function() {
    if (this[0] == this[0]) { 
      this[1] + this[1] 
    }; // I know this will simple double [1] values :(
});

desired result should be

[["A", 40], ["B", 20], ["C",30]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a plain javascript way to do it that collects the unique indexes in a map and totals them as it does, then regenerates the array with the totals:

abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]];

var items = {}, base, key;
for (var i = 0; i < abcArr.length; i++) {
    base = abcArr[i];
    key = base[0];
    // if not already present in the map, add a zeroed item in the map
    if (!items[key]) {
        items[key] = 0;
    }
    // add new item to the map entry
    items[key] += base[1];
}

// Now, generate new array
var outputArr = [], temp;
for (key in items) {
    // create array entry for the map value
    temp = [key, items[key]]
    // put array entry into the output array
    outputArr.push(temp);
}

// outputArr contains the result

Working demo: http://jsfiddle.net/jfriend00/vPMwu/


Here's a way using jQuery's .each:

abcArr = [["A", 10], ["B", 20], ["A",30],["C",40]];

var items = {}, base, key;
$.each(abcArr, function(index, val) {
    key = val[0];
    if (!items[key]) {
        items[key] = 0;
    }
    items[key] += val[1];
});

var outputArr = [];
$.each(items, function(key, val) {
    outputArr.push([key, val]);
});

// outputArr contains the result
document.body.innerHTML = JSON.stringify(outputArr);

Working demo: http://jsfiddle.net/jfriend00/Q8LLT/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...