25

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': 'bd@gmail.com'},
{'associationName': 'NaVi', 'firstName': 'John', 'lastName': 'Malkovich', 'email': 'jm@gmail.com'},
{'associationName': 'EG', 'firstName': 'Charles', 'lastName': 'Darwin', 'email': 'cd@gmail.com'}
];

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.

Simon
  • 19,658
  • 27
  • 149
  • 217
user3379856
  • 251
  • 1
  • 3
  • 3

3 Answers3

45

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'));
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • It works on numeric / bool typed fields only. @Alexandre Is there any solution to compare two strings? Kindly share your suggestion. Thanks. – Kamlesh Jun 18 '21 at 10:41
19
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);
zeed
  • 285
  • 1
  • 5
  • 18
ifredom
  • 979
  • 9
  • 6
1
 final data = [
  EmployerModel(id: "1", image: "", name: "A"),
  EmployerModel(id: "1", image: "", name: "A"),
  EmployerModel(id: "1", image: "", name: "B"),
  EmployerModel(id: "1", image: "", name: "B"),
  EmployerModel(id: "1", image: "", name: "C"),
  EmployerModel(id: "1", image: "", name: "E"),
  EmployerModel(id: "1", image: "", name: "E"),
  EmployerModel(id: "1", image: "", name: "E"),
  EmployerModel(id: "1", image: "", name: "G"),
];
var firstAlph = data[0].name![0];
List<Map<String, dynamic>> d = [];
data.forEach((element) {
  if (element.name![0] == firstAlph) {
    if (d.isEmpty) {
      d.add({
        firstAlph: [element],
      });
    } else {
      d.forEach((e) {
        if (e.keys.contains(firstAlph)) {
          e[firstAlph].add(element);
        }
      });
    }
  } else {
    firstAlph = element.name![0];
    d.add({
      firstAlph: [element],
    });
  }
});
debugPrint(d.toString());

This will give a List in alphabetical order which will make you're UI look much better. Output example:

["A":[data,data,data],"B":[data,data,data]]
Karan Gore
  • 21
  • 1