Home > database >  How to sort a list of unordered values in dart?
How to sort a list of unordered values in dart?

Time:12-16

Below is the program I tried but couldn't get expected results,

void main() {
  List data = ['Jan-21','Feb-21','Aug-21','Jan-22','Jun-21','Sept-22','Mar-21','Apr-22'];
  data.sort((a,b){
    return a.compareTo(b);
  });
  print(data.toString());
  //output - [Apr-22, Aug-21, Feb-21, Jan-21, Jan-22, Jun-21, Mar-21, Sept-22]
  //expected - [Jan-21, Feb-21, Mar-21, Aug-21, Jan-22, Apr-22, Jun-21, Sept-22]
}

I need to sort a list of "months-year" data as per the order in which they actually come,

for this list [Jan-21,Feb-21,Aug-21,Jan-22,Jun-21,Sept-22,Mar-21,Apr-22]

The output expected is [Jan-21, Feb-21, Mar-21, Aug-21, Jan-22, Apr-22, Jun-21, Sept-22]

CodePudding user response:

List<String> getSortedDates(List<String> dates){

  //Formatting for acceptable DateTime format
  DateFormat formatter = DateFormat("MMM-yy");

  //Mapping to convert into appropriate dateFormat
  List<DateTime> _formattedDates = dates.map(formatter.parse).toList();

  //Apply sort function on formatted dates
  _formattedDates.sort();

  //Mapping through sorted dates to return a List<String> with same formatting as passed List's elements
  return _formattedDates.map(formatter.format).toList();

}

CodePudding user response:

You can sort directly by overriding the sort function to sort by datetime.

 DateFormat formatter = DateFormat("MMM-yy");
 data.sort((a, b) => formatter.parse(a)
       .compareTo(formatter.parse(b)));

CodePudding user response:

You have to convert to date and use intl and then you can sort them

Note: you have set month name length to prevent the pattern problem

jun => MMM

sept => MMMM

    void main() {
  List data = [
    'Jan-21',
    'Feb-21',
    'Aug-21',
    'Jan-22',
    'Jun-21',
//     'Sept-22', // you have set month name length same to prevent the pattern problem
    'Mar-21',
    'Apr-22'
  ];
  data.sort((a, b) {
    var formattedDateA = intl.DateFormat("MMM-yy").parse(a);
    var formattedDateB = intl.DateFormat("MMM-yy").parse(b);
    
    return formattedDateA.compareTo(formattedDateB);
  });
  print(data.toString());
  //output - [Jan-21, Feb-21, Mar-21, Jun-21, Aug-21, Jan-22, Apr-22]
}
  • Related