I need to alphabetize a list of software versions in Angular from latest to oldest (i.e. 1.10.3.e, 1.9.5.b, 1.7.3, 1.5.1.c). I have been using .sort() which sorts alphabetically but treats the values as a string resulting in any 1.10 version to be sorted after a 1.5 version as it looks at the 1 and 0 independently.I tried doing .sort((a, b) => b - a) and it completely randomized the list rather than sorting it. I have also tried using .slice('.') which does not seem to work.
Any ideas?
Solution 1): temporary pad with '0':
(If a part of the version number could become more than 2 digits, padStart could be changed to 3, 4, ...)
var vers = [ '1.10.3.e', '1.9.5.b', '1.7.3', '1.5.1.c' ];
console.log( vers );
var temp = vers.map( function( s ){
return s.split('.').map( function( n ){ return n.padStart(2,'0'); } ).join('.');
} )
temp.sort();
vers = temp.map( function( s ){
return s.split('.').map( function( n ){ return n.replace(/^0+/, ''); } ).join('.');
} )
console.log( temp );
console.log( vers );
Solution 2): sort seperately by integers and strings.
I would call this the more elegant solution, even if it is a bit more complicated.
(Such an answer, with integers, has been given already)