I have such JSON data:
var jsondata = [
{
data: 'MacOS Sierra 10.12.13'
},
{
data: 'MacOS Sierra 10.12.5'
}
];
I need to select newest version of MacOS in this array. How to implement in better? I've tried to remove all alpha-numeric values and convert versions of mac to integers but it might not work in some situations (for example 101213 will be bigger then 10135).
Will really appreciate your help.
You can just split the strings into an array and then compare each element. I wrote a simple function to do this. Something like this should work
https://jsfiddle.net/3xmjmjsb/8/
function compare_versions(ver1,ver2){
var version1=ver1.replace(/[^0-9.]/g, "").split('.');
var version2=ver2.replace(/[^0-9.]/g, "").split('.');
for (var i=0, l=version1.length; i<l; i++) {
if(parseInt(version1[i])>parseInt(version2[i]))
{return ver1;}
else if(parseInt(version1[i])<parseInt(version2[i]))
{return ver2;}
}
return false;
}
and use it like this
var jsondata = [
{
data: 'MacOS Sierra 10.12.13'
},
{
data: 'MacOS Sierra 10.12.11'
}
];
var newest_version=compare_versions(jsondata[0]["data"],jsondata[1]["data"]);
if(newest_version){
alert(newest_version);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With