1

Given a List<String> of months, how do I create my own sort method in Dart?
Consider this relevant link.

The sorting order would be:

["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

Example

Given:

List<String> months = ["October", "January", "July"];

The expected output is:

["January", "July", "October"]
Ivanm
  • 119
  • 8

1 Answers1

1

You can make use of the List.sort method.
With the sorting order you provided, you can use indexOf to get an integer value that represent the sorting "weight" and then use num.compareTo to return a negative value if element a should appear before element b, i.e. the indexOf value is smaller, and a positive value if it should appear after element b:

const List<String> sortingOrder = ['January', 'February', 'March', 'April',
  'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

List<String> months = ['October', 'January', 'July'];
months.sort((a, b) => sortingOrder.indexOf(a).compareTo(sortingOrder.indexOf(b)));

print(months); // [January, July, October]

This way, you can obviously very easily create any kind of sorting order that sorts different kinds of values.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • 2
    .indexOf would be expensive to use repeatedly. You should create a map that maps January to 1, February to 2, and so on, and sort by that. – Randal Schwartz Jul 17 '19 at 18:37