Sort version-dotted number strings in Javascript?

前端 未结 14 1749
栀梦
栀梦 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:33

    This can be in an easier way using the sort method without hardcoding any numbers and in a more generic way.

    enter code here
    
    var arr = ['5.1.2', '5.1.1', '5.1.1', '5.1.0', '5.7.2.2'];
    
    splitArray = arr.map(elements => elements.split('.'))
    
    //now lets sort based on the elements on the corresponding index of each array
    
    //mapped.sort(function(a, b) {
    //  if (a.value > b.value) {
    //    return 1;
    //  }
    //  if (a.value < b.value) {
    //    return -1;
    //  }
    //  return 0;
    //});
    
    //here we compare the first element with the first element of the next version number and that is [5.1.2,5.7.2] 5,5 and 1,7 and 2,2 are compared to identify the smaller version...In the end use the join() to get back the version numbers in the proper format.
    
    sortedArray = splitArray.sort((a, b) => {
      for (i in a) {
        if (parseInt(a[i]) < parseInt(b[i])) {
          return -1;
          break
        }
        if (parseInt(a[i]) > parseInt(b[i])) {
          return +1;
          break
        } else {
          continue
        }
      }
    }).map(p => p.join('.'))
    
    sortedArray = ["5.1.0", "5.1.1", "5.1.1", "5.1.2", "5.7.2.2"]

提交回复
热议问题