0

I want to sort the array of Java versions asc or desc. I m looking for a regex pattern which can be used for solving. Please let me know if anyone can help.

Eg arr: ['1.4.2_01', '1.4.11_01', '1.8.0_131', '1.6.0_45', '1.8.0_72', '9.2.4', '9.0.1']

Sahil Mittal
  • 20,697
  • 12
  • 65
  • 90

2 Answers2

0

In java you can use :

String arr[] = {"1.4.2_01", "1.8.0_131", "1.6.0_45", "1.8.0_72", "9.2.4", "9.0.1"};
Arrays.sort(arr);

Output

System.out.println(Arrays.toString(arr));
[1.4.2_01, 1.6.0_45, 1.8.0_131, 1.8.0_72, 9.0.1, 9.2.4]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

You can sort it by the following implementation:

var versions = ["1.4.2_01", "1.6.0_45", "1.8.0_72", "1.8.0_131", "9.0.1", "9.2.4"];

var compare = function(v1,v2){

   v1splitted = v1.split('_');
   v2splitted = v2.split('_');

   if(v1splitted[0] === v2splitted[0]){
       if(parseInt(v1splitted[1]) > parseInt(v2splitted[1])){
           return 1;
       }
       return -1;
   }

    return (v1 > v2) ? 1 : -1 
}

var sortedVersions = versions.sort(compare);
// ["1.4.2_01", "1.6.0_45", "1.8.0_72", "1.8.0_131", "9.0.1", "9.2.4"]
Frank Roth
  • 6,191
  • 3
  • 25
  • 33
  • Hi Frank thanks for the answer. This is not working for the following array ['1.4.2_01', '1.4.11_01', '1.8.0_131', '1.6.0_45', '1.8.0_72', '9.2.4', '9.0.1']. I have updated the question. – user2971450 Apr 24 '17 at 10:47