jQuery的阵列组通过 [英] jquery array group by

查看:137
本文介绍了jQuery的阵列组通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数组这样

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

我如何才能通过组和值A,B,C ...

  $。每个(abcArr,函数(){
    如果(本[0] ==本[0]){
      这个[1] +这个[1]
    }; //我知道这简单的双[1] :(值
});

期望的结果应该是

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


解决方案

下面是一个普通的JavaScript方式做到这一点,它收集的唯一索引以地图和汇总他们,因为它的话,那么再生的总计数组:

  abcArr = [[A,10],[B,20],[A,30],[C,40];VAR项目= {},基地,重点;
对于(VAR I = 0; I< abcArr.length;我++){
    基地= abcArr [I]
    键=基本[0];
    //如果尚未美元地图p $ psent,在地图中添加的经过检查项目
    如果(!项目[关键]){
        项目[关键] = 0;
    }
    //新项目添加到地图项
    项目[键] + =基本[1];
}//现在,生成新的数组
VAR outputArr = [],温度;
为(以项目的关键){
    //创建一个映射值数组项
    TEMP = [键,项目[关键]
    //把数组进入输出数组
    outputArr.push(临时);
}// outputArr包含结果

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


下面是一个使用方式jQuery的。每个

  abcArr = [[A,10],[B,20],[A,30],[C,40];VAR项目= {},基地,重点;
$。每个(abcArr,函数(指数,VAL){
    键= VAL [0];
    如果(!项目[关键]){
        项目[关键] = 0;
    }
    项目[键] + = VAL [1];
});变种outputArr = [];
$。每次(项功能(键,VAL){
    outputArr.push([KEY,VAL]);
});// outputArr包含结果
document.body.innerHTML = JSON.stringify(outputArr);

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

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]]

解决方案

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/

这篇关于jQuery的阵列组通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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