skip to Main Content

I want to sort a personArray with age and name:

final personArray = [
  _Person(age: 10, name: 'Dean'),
  _Person(age: 20, name: 'Jack'),
  _Person(age: 30, name: 'Ben'),
  _Person(age: 30, name: 'Alice'),
];
personArray.sort((p1, p2) {
  return Comparable.compare(p1.age, p2.age);
});
for (final element in personArray) {
  print(element.name);
}

Console print: Dean Jack Ben Alice.

But what I want is: Dean Jack Alice Ben.

The pseudocode looks like:

personArray.sort((p1, p2) {
  return Comparable.compare(p1.age, p2.age) && Comparable.compare(p1.name, p2.name);
});

Anyway can do it?

2

Answers


  1. Change your compare function

    personArray.sort((p1, p2) {
          final compare = Comparable.compare(p1.age, p2.age);
          return compare == 0 ? Comparable.compare(p1.name, p2.name) : compare;
    });
    
    Login or Signup to reply.
  2. you can try this code

      personArray.sort((a, b) {
      return a.name.compareTo(b.name);
      });
    

    it will sort the objects with respect to name.

      personArray.sort((a, b) {
    if (a.age != b.age) {
      return a.age - b.age;
    }  else {
      return a.name.compareTo(b.name);
    }
    });
    

    and this will sort it first with age and if both the age are equal then it will sort the objects with respect to name.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search