先看圖:(我需要根據集裝尺寸和類型來統計數量)
效果:比較簡單,兩個循環就可以搞定
代碼實現:
1 let tempArr = []; 2 for (let i in containerList) { 3 let list = containerList[i]; 4 if (!(list.containerSize && list.containerType)) {// 如果 20GP 5 continue 6 }else { 7 let compare = {type:list.containerSize+'\''+list.containerType}//作比較的對象 (因為我需要這種格式,你也可以自定義格式) 8 if (tempArr.length==0) {//這段代碼必須要寫 9 let num = Number(list.containerCount); 10 let obj = { 11 type:list.containerSize+'\''+list.containerType, 12 total:num 13 } 14 tempArr.push(obj) 15 }else { 16 let flag = true; 17 for (let j in tempArr) {//這個循環只做一個操作,有相同類型的就進行統計 18 if (tempArr[j]["type"] == compare.type) { 19 tempArr[j]["total"] += Number(list.containerCount) 20 flag = false;//已經統計過的,就不要再重復了 21 break; 22 } 23 } 24 if (flag) {//如果沒有這種類型的,就push進去 25 let num = Number(list.containerCount); 26 var obj = { 27 type:list.containerSize+'\''+list.containerType, 28 total:num 29 } 30 tempArr.push(obj) 31 } 32 } 33 } 34 }