一維數(shù)組變二維再變一維

一維數(shù)組變二維數(shù)組,再變?yōu)橐痪S數(shù)組,F(xiàn)lutter實現(xiàn)

將一維object數(shù)組中某屬性值相同的元素分組。

一維:[{"a": "1"}, {"a": "1"}, {"a": 2}]
二維:==> [[{"a": "1"}, {"a": "1"}], [{"a": 2}]]
一維:==> [{"a": "1"}, {"a": ""}, {"a": 2}]

Flutter代碼:

Future<List<AModel>> _handleList(List<AModel> originList) async {

  var map = {};
  List<List<AModel>> dest = [];

  // 變?yōu)槎S數(shù)組
  for(var i = 0; i < originList.length; i++){
    var ai = originList[I];
    // 根據(jù) ai.dateString 分組
    if(map[ai.dateString] == null){
      dest.add([ai]);
      map[ai.dateString] = ai;
    } else {
      for(var j = 0; j < dest.length; j++){
        var dj = dest[j];
        if(dj.isNotEmpty && dj.first.dateString == ai.dateString){
          // 將屬性值相同的塞入數(shù)組
          dj.add(ai);
          break;
        }
      }
    }
  }
  print('dest count = ${dest.length}');

  List<AModel> tempArray = [];

  // 變?yōu)橐痪S數(shù)組
  for(int i = 0; i < dest.length;i++){
    List<AModel> tp = dest[i];
    for(int n = 0; n < tp.length; n++) {
      // 此處需要創(chuàng)建新的 AModel, 
      // 否則在下面修改的屬性值會導(dǎo)致數(shù)組元素全部被修改
      final map = tp[n].toJson(); 
      final tt = AModel.fromJson(map);  // 創(chuàng)建一個新的AModel
      if(n > 0){// 修改index > 0 的元素值為 “”
        tt.dateString = '';
      }
      tempArray.add(tt);
    }
  }
  print('fixed (e.dateString)');
  tempArray.forEach((e) {
    print('---${e.dateString}');
  });
  return tempArray;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容