Sorting files in alphabetical order

Viewed 253

I have a list of files like this :

['../page-1.png', '../page-3/png', '../page-2.png', '../page-6.png',  ... '../page-9.png']

I need to sort these files according to the number at the end. I am using this :

imagePaths.sort((a, b) =>
        a.toString().toLowerCase().compareTo(b.toString().toLowerCase()));

where imagePaths is the list of paths of those images.

THE ISSUE This method works fine until there are only single digit file numbers, i.e. if there is a file called, '../page-10.png', it gets sorted into the list like so :

['../page-1.png', '../page-10.png', '../page-11.png', '../page-12.png', '../page-2.png', ..]

Now, how to sort them in their correct order?

3 Answers

I think I could give you an idea. If the name pattern remains the same, then this gonna work out!

  var pages = [
    '../page-1.png',
    '../page-2.png',
    '../page-11.png',
    '../page-12.png',
    '../page-10.png',
  ];

  pages.sort((a, b) =>
      int.parse(a.split('-')[1].split('.')[0]).compareTo(int.parse(b.split('-')[1].split('.')[0])));
  
  print(pages);

//   [../page-1.png, ../page-2.png, ../page-10.png, ../page-11.png, ../page-12.png]

Just splitting the string and parsing the number and then sorting it.

Reference: https://api.dart.dev/stable/2.10.4/dart-core/Pattern-class.html

Hope that works!

A clean and safe solution will be by using a regex to extract the numbers instead of relying on the name format:

int parse(String page) {
   return int.tryParse(page.split(RegExp(r'[^\d]')).singleWhere((value) => int.tryParse(value) != null));
}

list.sort((a, b) => parse(a) > parse(b) ? 1 : -1);

Whist there are technical solutions to this, as per the other answers, the fundamental problem is that the files are not being named correctly if the intention is to sort them by name at some point. The numeric portion of the name should be given sufficient leading zeroes to handle the maximum number of files eg. page-0001.png, page-0002.png, etc.

Related