jquery数组分组

时间:2013-01-20 18:18:30

标签: jquery arrays

我有这样的数组

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

如何按A,B,C ......对数值进行分组和求和?

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

期望的结果应该是

[["A", 40], ["B", 20], ["C",30]]

3 个答案:

答案 0 :(得分:17)

这是一种简单的javascript方法,它可以收集地图中的唯一索引并按原样对它们进行总计,然后使用总计重新生成数组:

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

工作演示:http://jsfiddle.net/jfriend00/vPMwu/


这是使用jQuery的.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);

工作演示:http://jsfiddle.net/jfriend00/Q8LLT/

答案 1 :(得分:6)

Underscore.jsgroupBy,其余的可以map ping reduce来完成(也就是说,将每个组缩减为一个元素

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

var grouped = _.groupBy(abcArr, function(x){return x[0]})
var result  = _.map(grouped, function(x){
    return _.reduce(x, function(x,y){
        return [y[0], x[1]+y[1]];
    }, [,0])
})

http://jsfiddle.net/srvKQ/

或(缩小)

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

var result = _.map(
    _.groupBy(abcArr, function(x){return x[0]}),
    function(x){return _.reduce(
        x, function(x,y){return [y[0], x[1]+y[1]]}, [,0]
)});

http://jsfiddle.net/srvKQ/1/

答案 2 :(得分:0)

您可以使用onchange=""Array.reduce()

Map()