Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort two “numbers” with multiple dots

I have an unordered list that can look something like this:

1.1.1
1.1.1.1
1.1.2
1.10.1
1.10.2
1.2.1
1.2.2
1.2.3
1.2.4
1.20.1
1.3.1

And I want to sort it like "numerical" order in Javascript.

1.1.1
1.1.1.1
1.1.2
1.2.1
1.2.2
1.2.3
1.2.4
1.3.1
1.10.1
1.10.2
1.20.1

Which sort function I need?

like image 863
beowulf13th Avatar asked Jan 10 '14 17:01

beowulf13th


1 Answers

You can try:

Array.prototype.sortVersions = function() {
return this.map(function(e) {
  return e.split('.').map(function(e) {
    return parseInt(e)
   }
 )}).sort(function(a,b) {
   for (var i = 0; i < Math.max(a.length, b.length); i++) { 
     if (!a[i]) return -1; 
     if (!b[i]) return 1; 
     if (a[i]-b[i] != 0) return a[i]-b[i]; 
   } 
   return 0; 
 }).map(function(e) {
   return e.join('.')
 });
}

['1.1.1','1.1.1.1','1.1.2','1.10.1','1.10.2','1.2.1','1.2.2','1.2.3','1.2.4','1.20.1','1.3.1'].sortVersions()
like image 90
BroiSatse Avatar answered Oct 05 '22 05:10

BroiSatse