Created
January 22, 2020 17:17
-
-
Save oodavid/d4c843a7d88b42d0ff63f3bc7ef606d1 to your computer and use it in GitHub Desktop.
Dart > Sort List<Map> by multiple keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension SortBy on List { | |
sortBy(List<String> keys) { | |
this.sort((a, b) { | |
for(int k=0; k<keys.length; k++) { | |
String key = keys[k]; | |
int comparison = Comparable.compare((a[key]??""), (b[key]??"")); | |
if(comparison != 0){ | |
return comparison; | |
} | |
} | |
return 0; | |
}); | |
} | |
} | |
void main() { | |
List<Map> items = [ | |
{'building': 'Main Building', 'room': 'Lounge'}, | |
{'building': 'Another Building', 'room': 'Study'}, | |
{'building': 'Main Building', 'room': 'Kitchen'}, | |
{'building': 'Main Building'}, | |
{'building': 'Another Building', 'room': 'Kitchen'}, | |
]; | |
print(items); | |
print('----'); | |
items.sortBy(['building', 'room']); | |
print(items); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment