0

I want to sort the files present within a folder by their names. The following funtion is working very nicely, but sometimes it's not able to sort the files if the file names prepend with 0.

enter image description here

You can note that it could place 04 before 4, 05 before 5 and 06 before 6. But it could sort the other files.

This is the function code -

function sortAlphaNum(a, b) {
try {
    var reA = /[^a-zA-Z]/g;
    var reN = /[^0-9]/g;
    var AInt = parseInt(a, 10);
    var BInt = parseInt(b, 10);

    if (isNaN(AInt) && isNaN(BInt)) {
        var aA = a.replace(reA, "");
        var bA = b.replace(reA, "");
        if (aA === bA) {
            var aN = parseInt(a.replace(reN, ""), 10);
            var bN = parseInt(b.replace(reN, ""), 10);
            return aN === bN ? 0 : aN > bN ? 1 : -1;
        } else {
            return aA > bA ? 1 : -1;
        }
    } else if (isNaN(AInt)) {
        return 1;
    } else if (isNaN(BInt)) {
        return -1;
    } else {
        return AInt > BInt ? 1 : -1;
    }
}
catch(e) {
    alert(e + ': Line ' + e.line);
}

}

Can you please suggest me how to sort the files as they are shown in the windows explorer?

Thanks Nirmalya

Nirmalya
  • 398
  • 5
  • 19
  • You're looking for natural sorting. have a look [here](https://stackoverflow.com/questions/2802341/natural-sort-of-alphanumerical-strings-in-javascript) and [here](https://stackoverflow.com/questions/8107226/how-to-sort-strings-in-javascript-numerically) – Ghoul Fool Jun 10 '23 at 08:22

0 Answers0