Home > front end >  Sort a list of objects by multiple conditions in Dart
Sort a list of objects by multiple conditions in Dart

Time:01-31

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?

CodePudding user response:

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;
});

CodePudding user response:

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.

  • Related