how to sort strings in javascript numerically

前端 未结 7 1426
一个人的身影
一个人的身影 2021-02-14 12:48

I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings. I am not worried about signed or fl

相关标签:
7条回答
  • 2021-02-14 13:20

    I needed a way to take a mixed string and create a string that could be sorted elsewhere, so that numbers sorted numerically and letters alphabetically. Based on answers above I created the following, which pads out all numbers in a way I can understand, wherever they appear in the string.

    function padAllNumbers(strIn) {
        // Used to create mixed strings that sort numerically as well as non-numerically
        var patternDigits = /(\d+)/g; // This recognises digit/non-digit boundaries
        var astrIn = strIn.split( patternDigits ); // we create an array of alternating digit/non-digit groups
    
        var result = "";
    
        for (var i=0;i<astrIn.length;  i++) {
            if (astrIn[i] != "") { // first and last elements can be "" and we don't want these padded out
                if (isNaN(astrIn[i])) {
                    result += astrIn[i];
                } else {
                    result += padOneNumberString("000000000",astrIn[i]);
                }
            }
        }
        return result;
    }
    
    function padOneNumberString(pad,strNum,left) {
        // Pad out a string at left (or right)
        if (typeof strNum === "undefined") return pad;
        if (typeof left === "undefined") left = true;
        var padLen =  pad.length - (""+ strNum).length;
        var padding = pad.substr(0,padLen);
        return left?  padding + strNum : strNum + padding;
    }
    
    0 讨论(0)
提交回复
热议问题