how to sort strings in javascript numerically

前端 未结 7 1475
一个人的身影
一个人的身影 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:18

    Here's a more complete solution that sorts according to both letters and numbers in the strings

    function sort(list) {
        var i, l, mi, ml, x;
        // copy the original array
        list = list.slice(0);
    
        // split the strings, converting numeric (integer) parts to integers
        // and leaving letters as strings
        for( i = 0, l = list.length; i < l; i++ ) {
            list[i] = list[i].match(/(\d+|[a-z]+)/g);
            for( mi = 0, ml = list[i].length; mi < ml ; mi++ ) {
                x = parseInt(list[i][mi], 10);
                list[i][mi] = !!x || x === 0 ? x : list[i][mi];
            }
        }
    
        // sort deeply, without comparing integers as strings
        list = list.sort(function(a, b) {
            var i = 0, l = a.length, res = 0;
            while( res === 0 && i < l) {
                if( a[i] !== b[i] ) {
                    res = a[i] < b[i] ? -1 : 1;
                    break;
                }
    
                // If you want to ignore the letters, and only sort by numbers
                // use this instead:
                // 
                // if( typeof a[i] === "number" && a[i] !== b[i] ) {
                //     res = a[i] < b[i] ? -1 : 1;
                //     break;
                // }
    
                i++;
            }
            return res;
        });
    
        // glue it together again
        for( i = 0, l = list.length; i < l; i++ ) {
            list[i] = list[i].join("");
        }
        return list;
    }
    

提交回复
热议问题