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.