Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of maps in Dart - Second Level Sort in Dart

Tags:

sorting

dart

I have a list of maps like this:

var associations = [{'name': 'EG', 'description': 'Evil Genius'},
                    {'name': 'NaVi', 'description': 'Natus Vincere'}];

var members = [
{'associationName': 'EG', 'firstName': 'Bob', 'lastName': 'Dylan', 'email': '[email protected]'},
{'associationName': 'NaVi', 'firstName': 'John', 'lastName': 'Malkovich', 'email': '[email protected]'},
{'associationName': 'EG', 'firstName': 'Charles', 'lastName': 'Darwin', 'email': '[email protected]'}
];

I would like to write a code that would sort the list of members alphabetically by the last name first, then by the first name. Moreover, I would like to be able to find members whose lastnames start with a specifiedd letter. By example, with D, we would get Bob Dylan and Charles Darwin. I am able to manage it with a single map or a single list, but combining a list of maps makes it more difficult.

Thanks for your help.

like image 421
user3379856 Avatar asked Mar 04 '14 16:03

user3379856


People also ask

How do you sort a list of elements in darts?

We use the sort() method to sort the string elements of a list in alphabetical order (from A to Z or from Z to A).

Can you sort a map in Dart?

To sort a Map , we can utilize the SplayTreeMap . Sorted keys are used to sort the SplayTreeMap . A SplayTreeMap is a type of map that iterates keys in a sorted order.

How do you sort a list in ascending order flutter?

In Flutter DART if we want to sort our Number list in these format then we have to use the ListName. sort() method. This method allow us to sort the list into ascending order automatically. But again to sort list in descending order we have to use ListName.


2 Answers

To sort :

members.sort((m1, m2) {
  var r = m1["lastName"].compareTo(m2["lastName"]);
  if (r != 0) return r;
  return m1["firstName"].compareTo(m2["firstName"]);
});

To filter :

members.where((m) => m['lastName'].startsWith('D'));
like image 145
Alexandre Ardhuin Avatar answered Sep 22 '22 12:09

Alexandre Ardhuin


List<Map> myList = [
  { 'name' : 'ifredom','age':23},
  { 'name' : 'JackMa','age':61},
  { 'name' : 'zhazhahui','age':48},
];

myList.sort((a, b) => (b['age']).compareTo(a['age'])); /// sort List<Map<String,dynamic>>

print(myList);
like image 23
ifredom Avatar answered Sep 21 '22 12:09

ifredom