Reputation: 2206
What is the best way of sorting a map by its nested values in Dart?
Map myMap = {
'A':{'foo':'#', 'pos':2},
'B':{'baa':'#', 'pos':0},
'C':{'yay':'#', 'pos':1},
}
Map mySortedMap = myMap.sort() ???
print(mySortedMap)
Output:
{
'B':{'baa':'#', 'pos':0},
'C':{'yay':'#', 'pos':1},
'A':{'foo':'#', 'pos':2},
}
Upvotes: 0
Views: 217
Reputation: 2593
There is quite simple way: sort keys and create new map from those keys:
Map sortMapByPos(Map map) {
final sortedKeys = map.keys.toList(growable: false)
..sort((k1, k2) => ((map[k1]['pos'] - map[k2]['pos'])));
return Map.fromIterable(sortedKeys, key: (k) => k, value: (k) => map[k]);
}
Usage as below:
print(sortMapByPos(myMap));
Upvotes: 1