I have a map (mapone) that I want to sort by 'number'. But some items in the map have the same 'number', so if the items have the same 'number', they should be sorted by 'numbertwo'.
To sort by one value, I have this code. Is there an easy way to sort the map by two values as I have desciribed?
Map mapone = {
'1': {'number': 8,'numbertwo': 2},
'2': {'number': 2,'numbertwo': 9},
'3': {'number': 2,'numbertwo': 3},
'4': {'number': 9,'numbertwo': 1},
'5': {'number': 8,'numbertwo': 1},
};
mapone = Map.fromEntries(mapone.entries.toList()
..sort((e1, e2) => e1.value['number'].compareTo(e2.value['number'])));
CodePudding user response:
You can use this
mapone = Map.fromEntries(
mapone.entries.toList()
..sort(
(e1, e2) {
int a = e1.value['number'].compareTo(e2.value['number']);
if (a != 0) return a;
return e1.value['numbertwo'].compareTo(e2.value['numbertwo']);
},
),
);
Result
3: {number: 2, numbertwo: 3},
2: {number: 2, numbertwo: 9},
5: {number: 8, numbertwo: 1},
1: {number: 8, numbertwo: 2},
4: {number: 9, numbertwo: 1}
This question describe more.