jquery 数组分组依据 [英] jquery array group by

查看:38
本文介绍了jquery 数组分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组

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

如何按 A、B、C...对值进行分组和求和...

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 :(
});

想要的结果应该是

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

推荐答案

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

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

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

这是一种使用 jQuery 的 .each 的方法:

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

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

这篇关于jquery 数组分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆