一維數(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;
}