日期:2014-05-16  浏览次数:20375 次

JS头大问题,大家出下手
JS数组原型数据

var detailInfo = new Array();
detailInfo[0] = {PrdNo : "AX", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "AX_N" };
detailInfo[1] = {PrdNo : "AX", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "AX_N" };
detailInfo[2] = {PrdNo : "F001", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "绢丝块" };
detailInfo[3] = {PrdNo : "AX", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "AX_N" };
detailInfo[4] = {PrdNo : "F001", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "绢丝块" };
detailInfo[5] = {PrdNo : "AX", Color : "001", Spc : "1", Qty : "1", Zxno : "", PrdName : "AX_N" };
detailInfo[6] = {PrdNo : "AX", Color : "002", Spc : "1", Qty : "1", Zxno : "", PrdName : "AX_N" };

条件是:PrdNo、Color和Spc三者值都相同累加Qty,结果是想要变成新的数组如下

var newInfo = new Array();
newInfo[0] = {PrdNo : "AX", Color : "001", Spc : "1", Qty : "5", Zxno : "", PrdName : "AX_N" };
newInfo[1] = {PrdNo : "F001", Color : "001", Spc : "1", Qty : "2", Zxno : "", PrdName : "绢丝块" };

------解决方案--------------------
JScript code
var d = []; 
d[0] = {P : "a", C : "1", Q : 2}; 
d[1] = {P : "a", C : "1", Q : 1}; 
d[2] = {P : "b", C : "1", Q : 1}; 
d[3] = {P : "a", C : "2", Q : 1}; 

//排序
function compare(o1, o2){
    if(o1.P != o2.P) return o1.P.localeCompare(o2.P);
    else if(o1.C != o2.C) return o1.C.localeCompare(o2.C);
    else return 0;
}

var dd = d.sort(compare);

//比较
var n = [];

for(var i = 1, len = d.length; i < len; i++){
    if(d[0].P == d[1].P && d[0].C == d[1].C){
        d[1].Q += d[0].Q;
    }else{
        n.push(d[0]);
    }
    d.shift();
}
n.push(d[0]);



for(o in n){
    var s = "";
    for(oo in n[o]){
        s += oo+":"+n[o][oo]+"\n";
    }
    alert(s);
}