//原始数据,后台没有进行排序的 var rowData=[ {data:2,date:'01',code:'cr_2',name:'桥吊2'}, {data:1,date:'03',code:'cr_1',name:'桥吊1'}, {data:4,date:'06',code:'cr_1',name:'桥吊3'}, {data:111,date:'09',code:'cr_1',name:'桥吊1'}, {data:212,date:'02',code:'cr_2',name:'桥吊2'}, {data:222,date:'03',code:'cr_2',name:'桥吊2'}, {data:11,date:'07',code:'cr_1',name:'桥吊1'} ]; //需要的数据 var result1=[ {name:"cr_1",data:[1,4,11,111]}, {name:"cr_2",data:[2,212,222]} ]; //========================================================= //1.数组添加元素 var newAry = []; for(var i=0;i<rowData.length;i++){ //1.判断数组中是否包含该元素,不包含则添加,包含则追加子元素 var result = fun_IsExists(newAry,rowData[i].code); if(result.flag){ newAry[result.index].data.push(rowData[i].data); }else{ newAry.push({ name:rowData[i].code, data:[rowData[i].data] }); } newAry.push(); } //debugger; //2.对象数组排序(将cr_1根据名字进行排序) newAry.sort(compare("name")); //判断是否存在 function fun_IsExists(newAry,name){ var flag = false; var index = -1; for(var i=0;i<newAry.length;i++){ if(newAry[i].name == name){ index = i; flag = true; break; } } return { flag:flag, index:index }; } //排序 function compare(prop) { return function (obj1, obj2) { var val1 = obj1[prop]; var val2 = obj2[prop];if (val1 < val2) { return -1; } else if (val1 > val2) { return 1; } else { return 0; } } }