3

I am able to compare version numbers correctly in JavaScript without having to split and check each decimal numbers. How is it working?

("2.0.1" > "2.1.0")
false

("2.2.1" > "2.1.0")
true

("2.5.1" > "2.0.5")
true

Thanks.

4 Answers4

11

No, you're not " able to compare version numbers correctly in JavaScript without having to split"

"2.2.8" > "2.2.10" // true

Those strings are compared character after character, from left to right.

You do need to split and compare number after number, which is easy enough. Here's for example how you could implement it:

function Version(s){
  this.arr = s.split('.').map(Number);
}
Version.prototype.compareTo = function(v){
  for (var i=0; ;i++) {
    if (i>=v.arr.length) return i>=this.arr.length ? 0 : 1;
    if (i>=this.arr.length) return -1;
    var diff = this.arr[i]-v.arr[i]
    if (diff) return diff>0 ? 1 : -1;
  }
}

console.log((new Version("1.1.1")).compareTo(new Version("1.2.1"))); // -1

console.log((new Version("1.1.1")).compareTo(new Version("1.10.1"))); // -1

console.log((new Version("1.10.1.2")).compareTo(new Version("1.10.1"))); // 1

console.log((new Version("1.10.1.2")).compareTo(new Version("1.10.1.2"))); // 0
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

Because you're comparing strings lexicographically, which yields the same result in your examples. However, this won't work in all circumstances, like when you get into double digits: 2.15.29.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

I know this is old and already have a marked answer, but the below code works pretty well for me using localeCompare.

The function will return either:

  • 0: the version strings are equal

  • 1: the version a is greater than b

  • -1: the version b is greater than a

    function sort(a, b){
       return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
    }
    

The above works for angularJS and Javascript. The localeCompare() is an ES1 feature that is supported by all browsers.

For more detail on the usage refer to - https://www.w3schools.com/jsref/jsref_localecompare.asp

RBT
  • 24,161
  • 21
  • 159
  • 240
Cito
  • 26
  • 6
  • That won't work with double digits. e.g. 1.2.3 will be marked bigger than 1.11.3. – gbero Oct 18 '22 at 06:37
  • You didn't try it but just assumed it won't work on double digits. Try the code and see that 1.11.3 is bigger than 1.2.3. You can try it on the w3schools link I posted @gbero – Cito Oct 20 '22 at 17:10
  • 1
    I tried it back then, and just retried it and it doesn't work ;-) – gbero Jan 06 '23 at 10:38
-1

better way to compare is to create a version number float and then a sub version number, like shown below

subVersion = parseInt(fullVersion.split(".")[2]);
mainVersion = parseFloat(fullOsVer);

after this conversion, you can do comparison. this comparison will be comparing two integers.

Oxi
  • 2,918
  • 17
  • 28