Skip to content

Natural sort #116

@freefly42

Description

@freefly42

I use this for giving access to build distributions hosted in private S3 buckets, and find that alphanumeric sorting results in confusion over what the "latest" build is. So I added a natural sort function that I call on the directories and the folders so that "99.txt" will appear before "100.txt". Actually, in my implementation I now reverse sort the numbers so that the highest build number will always be at the top of the list, but the text portions are sorted alphabetically:

function naturalSort(a, b) {
  // Extract strings and numbers from filenames
  var regex = /(\D+)|(\d+)/g;
  var aParts = a.Key.match(regex);
  var bParts = b.Key.match(regex);

  // Compare corresponding parts of the filenames
  while (aParts && bParts && aParts.length > 0 && bParts.length > 0) {
    var aPart = aParts.shift();
    var bPart = bParts.shift();
    if (aPart !== bPart) {
      var aNum = parseInt(aPart, 10);
      var bNum = parseInt(bPart, 10);
      if (isNaN(aNum) || isNaN(bNum)) {
        // Sort by string part
        return aPart.localeCompare(bPart);
      } else {
        // Sort by numerical part
        if (aNum !== bNum) {
          return bNum - aNum;
        }
      }
    }
  }

  // If filenames have different numbers of parts, sort by length
  return aParts.length - bParts.length;
}

It works by splitting the names by "decimal" vs "not-decimal" segments, and if a corresponding segment of both names is numeric it Performas a numerical sorting, if either is non-numeric than alphabetical sorting is used. The result is that natural number sorting will occur regardless of where in the file/directory name the number appears. Since this is done in the browser I don't care much that it's less efficient than other sorting mechanisms, it produces highly desirable results.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions