Sort version-dotted number strings in Javascript?

前端 未结 14 1750
栀梦
栀梦 2020-12-05 15:01

I have an array of following strings:

[\'5.5.1\', \'4.21.0\', \'4.22.0\', \'6.1.0\', \'5.1.0\', \'4.5.0\'] 

...etc.

I need a soluti

14条回答
  •  忘掉有多难
    2020-12-05 15:45

    Inspired from the accepted answer, but ECMA5-compatible, and with regular string padding (see my comments on the answer):

    function sortCallback(a, b) {
    
        function padParts(version) {
            return version
                .split('.')
                .map(function (part) {
                    return '00000000'.substr(0, 8 - part.length) + part;
                })
                .join('.');
        }
    
        a = padParts(a);
        b = padParts(b);
    
        return a.localeCompare(b);
    }
    

    Usage:

    ['1.1', '1.0'].sort(sortCallback);
    

提交回复
热议问题