The (most of the time) correct JavaScript answer in 2020
Both Nina Scholz in March 2020 and Sid Vishnoi in April 2020 post the modern answer:
var versions = ["2.0.1", "2.0", "1.0", "1.0.1", "2.0.0.1"];
versions.sort((a, b) =>
a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);
console.log(versions);
localCompare has been around for some time
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator
But what about 1.0a and 1.0.1
localCompare doesn't solve that, still returns 1.0.1 , 1.0a
Michael Deal in his (longish &complex) solution already cracked that in 2013
He converts Numbers to another Base, so they can be sorted better
His answer got me thinking...
666 - Don't think in numbers - 999
Sorting is alphanumeric, based on the ASCII values, so let's (ab)use ASCII as the "base"
My solution is to convert 1.0.2.1 to b.a.c.b to bacb , and then sort
This solves 1.1 vs. 1.0.0.0.1 with: bb vs. baaab
And immediately solves the 1.0a and 1.0.1 sorting problem with notation: baa and bab
Conversion is done with:
const str = s => s.match(/(\d+)|[a-z]/g)
.map(c => c == ~~c ? String.fromCharCode(97 + c) : c);
= Calculate ASCII value for 0...999 Numbers, otherwise concat letter
1.0a
>>> [ "1" , "0" , "a" ]
>>> [ "b" , "a" , "a" ]
For comparison sake there is no need to concatenate it to one string with .join("")
Oneliner
const sortVersions=(x,v=s=>s.match(/(\d+)|[a-z]/g)
.map(c=>c==~~c?String.fromCharCode(97+c):c))
=>x.sort((a,b)=>v(b)<v(a)?1:-1)
Test snippet:
function log(label,val){
document.body.append(label,String(val).replace(/,/g," - "),document.createElement("BR"));
}
let v = ["1.90.1", "1.9.1", "1.89", "1.090", "1.2", "1.0a", "1.0.1", "1.10", "1.0.0a"];
log('not sorted input :',v);
v.sort((a, b) => a.localeCompare(b,undefined,{numeric:true,sensitivity:'base' }));
log(' locale Compare :', v); // 1.0a AFTER 1.0.1
const str = s => s.match(/(\d+)|[a-z]/g)
.map(c => c == ~~c ? String.fromCharCode(97 + c) : c);
const versionCompare = (a, b) => {
a = str(a);
b = str(b);
return b < a ? 1 : a == b ? 0 : -1;
}
v.sort(versionCompare);
log('versionCompare:', v);
Note how 1.090 is sorted in both results.
My code will not solve the 001.012.001 notation mentioned in one answer, but the localeCompare
gets that part of the challenge right.
You could combine the two methods:
- sort with
.localCompare
OR versionCompare
when there is a letter involved
Final JavaScript solution
const sortVersions = (
x,
v = s => s.match(/[a-z]|\d+/g).map(c => c==~~c ? String.fromCharCode(97 + c) : c)
) => x.sort((a, b) => (a + b).match(/[a-z]/)
? v(b) < v(a) ? 1 : -1
: a.localeCompare(b, 0, {numeric: true}))
let v=["1.90.1","1.090","1.0a","1.0.1","1.0.0a","1.0.0b","1.0.0.1"];
console.log(sortVersions(v));
2001403
, is it2.0.14.3
or20.1.4.3
or2.0.1.43
? This approach is limiting if not flawed.