Here is the software version number:
"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"
How can I compare this?? Assume the correct order is:
"1.0", "1.0.1", "2.0", "2.0.0.1", "2.0.1"
The idea is simple...: Read the first digit, than, the second, after that the third.... But I can't convert the version number to float number.... You also can see the version number like this:
"1.0.0.0", "1.0.1.0", "2.0.0.0", "2.0.0.1", "2.0.1.0"
and this is more clear to see what is the idea behind... But, how to convert it into a computer program?? Do any one have any idea on how to sorting this? Thank you.
The basic idea to make this comparison would be to use
Array.split
to get arrays of parts from the input strings and then compare pairs of parts from the two arrays; if the parts are not equal we know which version is smaller.There are a few of important details to keep in mind:
Here's the code for an implementation that you can use directly (gist with documentation):
This version compares parts naturally, does not accept character suffixes and considers "1.7" to be smaller than "1.7.0". The comparison mode can be changed to lexicographical and shorter version strings can be automatically zero-padded using the optional third argument.
There is a JSFiddle that runs "unit tests" here; it is a slightly expanded version of ripper234's work (thank you).
Important note: This code uses
Array.map
andArray.every
, which means that it will not run in IE versions earlier than 9. If you need to support those you will have to provide polyfills for the missing methods.My less verbose answer than most of the answers here
The idea is comparate two versions and know which is the biggest. We delete "." and we compare each position of the vector with the other.
One more implementation I believe worth sharing as it's short, simple and yet powerful. Please note that it uses digit comparison only. Generally it checks if version2 is later than version1 and returns true if it's the case. Suppose you have version1: 1.1.1 and version2: 1.1.2. It goes through each part of the two versions adding their parts as follows: (1 + 0.1) then (1.1 + 0.01) for version1 and (1 + 0.1) then (1.1 + 0.02) for version2.
If you want to find the latest version out of list of versions then this might be useful:
Check the function
version_compare()
from the php.js project. It's is similar to PHP'sversion_compare()
.You can simply use it like this:
couldnt you convert them into numbers and then sort after size? Append 0's to the ones to the numbers that are < 4 in length
played around in console:
bigger the version, the bigger number. Edit: probably needs adjusting to account for bigger version series