Skip to content
Advertisement

How is version number comparison working correctly in JavaScript?

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement