sortBy method
Sorts a list of maps by the given key.
key
is the key to sort by.
If isDesc
is true, the list will be sorted in descending order.
Example:
final sortedMaps = list.sortBy("price");
Implementation
List<Map<T, T>> sortBy(String key, {bool isDesc = false}) {
final List<Map<T, T>> maps = whereType<Map<T, T>>()
.where((Map<T, T> element) => element.containsKey(key))
.toList();
try {
maps.sort((Map<T, T> a, Map<T, T> b) {
final T? aValue = a[key];
final T? bValue = b[key];
if (aValue is Comparable && bValue is Comparable) {
return aValue.compareTo(bValue);
}
throw ArgumentError('Values for key "$key" must be comparable');
});
} on ArgumentError {
return <Map<T, T>>[];
}
return isDesc ? maps.reversed.toList() : maps;
}