Reputation:
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.
Upvotes: 4
Views: 3692
Reputation: 36
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
Upvotes: 1
Reputation: 2968
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.
Upvotes: -1
Reputation: 382344
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
Upvotes: 11
Reputation: 522480
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
.
Upvotes: 4