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.
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:
This example demonstrates how to implement custom sorting logic in Dart, both for built-in types and custom objects.