Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check for latest version of OS in JSON

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.

like image 549
Oleg V Avatar asked Nov 07 '22 20:11

Oleg V


1 Answers

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);
    }
like image 131
George Pant Avatar answered Nov 15 '22 05:11

George Pant