how to sort strings in javascript numerically

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

    Use this compare function for sorting ..

    function compareLists(a,b){
        var alist = a.split(/(\d+)/), // split text on change from anything to digit and digit to anything
            blist = b.split(/(\d+)/); // split text on change from anything to digit and digit to anything
    
        alist.slice(-1) == '' ? alist.pop() : null; // remove the last element if empty
        blist.slice(-1) == '' ? blist.pop() : null; // remove the last element if empty
    
        for (var i = 0, len = alist.length; i < len;i++){
            if (alist[i] != blist[i]){ // find the first non-equal part
               if (alist[i].match(/\d/)) // if numeric
               {
                  return +alist[i] - +blist[i]; // compare as number
               } else {
                  return alist[i].localeCompare(blist[i]); // compare as string
               }
            }
        }
    
        return true;
    }
    

    Syntax

    var data = ["a1b3","a10b11","b10b2","a9b2","a1b20","a1c4"];
    data.sort( compareLists );
    alert(data);
    

    demo at http://jsfiddle.net/h9Rqr/7/

提交回复
热议问题