js簡單數組分類計算(兩個循環搞定)


先看圖:(我需要根據集裝尺寸和類型來統計數量)

效果:比較簡單,兩個循環就可以搞定

 

代碼實現:

 

 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                 }

 

 

 

 
        
 
        
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM