Sorting By Functions in Dart

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Dart.

import 'dart:collection';

void main() {
  var fruits = ['peach', 'banana', 'kiwi'];

  // We implement a comparison function for string lengths.
  int lenCmp(String a, String b) {
    return a.length.compareTo(b.length);
  }

  // Now we can call sort with this custom comparison function
  // to sort `fruits` by name length.
  fruits.sort(lenCmp);
  print(fruits);

  // We can use the same technique to sort a list of
  // values that aren't built-in types.
  class Person {
    String name;
    int age;

    Person(this.name, this.age);

    @override
    String toString() => '($name, $age)';
  }

  var people = [
    Person('Jax', 37),
    Person('TJ', 25),
    Person('Alex', 72),
  ];

  // Sort `people` by age using a custom comparison function.
  people.sort((a, b) => a.age.compareTo(b.age));
  print(people);
}

In this Dart example, we’re using the sort method available on Dart lists to perform custom sorting. The sort method can take an optional comparison function as an argument.

For the string length comparison, we define a lenCmp function that compares the lengths of two strings. We then pass this function to fruits.sort() to sort the list of fruits by their length.

For sorting custom objects like Person, we directly pass an anonymous function to people.sort(). This function compares the age property of two Person objects.

Note that in Dart, we don’t need to use a separate package for comparison operations as we did with cmp.Compare in the original example. Dart’s built-in compareTo method on int and other comparable types serves this purpose.

To run this Dart program, save it to a file (e.g., sorting_by_functions.dart) and use the Dart command-line interface:

$ dart sorting_by_functions.dart
[kiwi, peach, banana]
[(TJ, 25), (Jax, 37), (Alex, 72)]

This example demonstrates how to implement custom sorting logic in Dart, both for built-in types and custom objects.