how to sort strings in javascript numerically

前端 未结 7 1513
一个人的身影
一个人的身影 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条回答
  •  Happy的楠姐
    2021-02-14 13:01

    I think this does what you want

    function sortArray(arr) {
        var tempArr = [], n;
        for (var i in arr) {
            tempArr[i] = arr[i].match(/([^0-9]+)|([0-9]+)/g);
            for (var j in tempArr[i]) {
                if( ! isNaN(n = parseInt(tempArr[i][j])) ){
                    tempArr[i][j] = n;
                }
            }
        }
        tempArr.sort(function (x, y) {
            for (var i in x) {
                if (y.length < i || x[i] < y[i]) {
                    return -1; // x is longer
                }
                if (x[i] > y[i]) {
                    return 1;
                }
            }
            return 0;
        });
        for (var i in tempArr) {
            arr[i] = tempArr[i].join('');
        }
        return arr;
    }
    alert(
        sortArray(["a1b3", "a10b11", "a10b2", "a9b2"]).join(",")
    );
    

提交回复
热议问题