how to sort strings in javascript numerically

前端 未结 7 1459
一个人的身影
一个人的身影 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条回答
  •  梦毁少年i
    2021-02-14 13:10

    Assuming what you want to do is just do a numeric sort by the digits in each array entry (ignoring the non-digits), you can use this:

    function sortByDigits(array) {
        var re = /\D/g;
    
        array.sort(function(a, b) {
            return(parseInt(a.replace(re, ""), 10) - parseInt(b.replace(re, ""), 10));
        });
        return(array);
    }
    

    It uses a custom sort function that removes the digits and converts to a number each time it's asked to do a comparison. You can see it work here: http://jsfiddle.net/jfriend00/t87m2/.

    If this isn't what you want, then please clarify as your question is not very clear on how the sort should actually work.

提交回复
热议问题