Skip to content

Instantly share code, notes, and snippets.

@oodavid
Created January 22, 2020 17:17
Show Gist options
  • Save oodavid/d4c843a7d88b42d0ff63f3bc7ef606d1 to your computer and use it in GitHub Desktop.
Save oodavid/d4c843a7d88b42d0ff63f3bc7ef606d1 to your computer and use it in GitHub Desktop.
Dart > Sort List<Map> by multiple keys
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