Here is a 'better' solution on my opinion (because the checked one modifies the original array, and this is evil ;) ) :
function latest(versions) {
return versions.reduce(function(latest, current){
var l = latest.split('.'),
c = current.split('.');
for (var i=0,len=Math.min(l.length, c.length); i<len; i++){
if (+l[i] === +c[i]) {
continue;
} else {
return +l[i] < +c[i] ? current : latest;
}
}
return l.length < c.length ? current : latest;
}, "0");
}
The results are exactly the same than the checked answer, except the original array is still pristine.
[
latest (['1.2.5.4', '1.3.5.3', '1.2.3.4.5', '1.24.2.1', '1.2.52']),
latest (['1.2.5.4', '1.3.5.3', '1.2.3.4.5', '1.2.52']),
latest (['1.2.5.4', '1.2.3.4.5', '1.2.52']),
latest (['1.2.5.4', '1.2.3.4.5'])
]
/* Displays on JS console
["1.24.2.1", "1.3.5.3", "1.2.52", "1.2.5.4"]
*/
And it takes advantage from the reduce
function, which is exactly made for this usage.