sorting version numbers stored as string in an array

Viewed 1565

Say I have an array like this:

let arr = ["1.2.5", "1", "10", "2.0.4", "3.3.3.3"];

What would be the best way to sort this and get result like this:
let arr = ["1", "1.2.5", "2.0.4", "3.3.3.3", "10"];

First I thought of converting each item in the array into 'float' may work but then multiple decimals won't give expected results.

I can also go for a for loop and doing stuff like item.split(".") and then check one by one, but I do not think this is the best way.

Any suggestions, please?

5 Answers
  • sort 1.0a notation correct
  • use native localeCompare to sort 1.090 notation

function log(label,val){
  document.body.append(label,String(val).replace(/,/g," - "),document.createElement("BR"));
}

const sortVersions = (
  x,
  v = s => s.match(/[a-z]|\d+/g).map(c => c==~~c ? String.fromCharCode(97 + c) : c)
) => x.sort((a, b) => (a + b).match(/[a-z]/) 
                             ? v(b) < v(a) ? 1 : -1 
                             : a.localeCompare(b, 0, {numeric: true}))

let v=["1.90.1","1.090","1.0a","1.0.1","1.0.0a","1.0.0b","1.0.0.1","1.0a"];
log(' input : ',v);
log('sorted: ',sortVersions(v));
log('no dups:',[...new Set(sortVersions(v))]);

Related