Here, in my opinion, the “best” solution (because the proven 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 as the verified answer, except that the original array is still untouched.
[
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 of a function reducethat is designed specifically for this use.
source
share