Sort version-dotted number strings in Javascript?

前端 未结 14 1695
栀梦
栀梦 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:40
    **Sorted Array Object by dotted version value**
    
        var sampleData = [
          { name: 'Edward', value: '2.1.2' },
          { name: 'Sharpe', value: '2.1.3' },
          { name: 'And', value: '2.2.1' },
          { name: 'The', value: '2.1' },
          { name: 'Magnetic', value: '2.2' },
          { name: 'Zeros', value: '0' },
          { name: 'Zeros', value: '1' }
        ];
        arr = sampleData.map( a => a.value).sort();
        var requireData = [];
    
        arr.forEach(function(record, index){    
          var findRecord = sampleData.find(arr => arr.value === record);
            if(findRecord){
              requireData.push(findRecord);
            }
          });
        console.log(requireData);
    
        [check on jsfiddle.net][1]
        [1]: https://jsfiddle.net/jx3buswq/2/
    
        It is corrected now!!!
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题