I have an unordered list that can look something like this:
1.1.1
1.1.1.1
1.1.2
1.10.1
1.10.2
1.2.1
1.2.2
1.2.3
1.2.4
1.20.1
1.3.1
And I want to sort it like "numerical" order in Javascript.
1.1.1
1.1.1.1
1.1.2
1.2.1
1.2.2
1.2.3
1.2.4
1.3.1
1.10.1
1.10.2
1.20.1
Which sort function I need?
You can try:
Array.prototype.sortVersions = function() {
return this.map(function(e) {
return e.split('.').map(function(e) {
return parseInt(e)
}
)}).sort(function(a,b) {
for (var i = 0; i < Math.max(a.length, b.length); i++) {
if (!a[i]) return -1;
if (!b[i]) return 1;
if (a[i]-b[i] != 0) return a[i]-b[i];
}
return 0;
}).map(function(e) {
return e.join('.')
});
}
['1.1.1','1.1.1.1','1.1.2','1.10.1','1.10.2','1.2.1','1.2.2','1.2.3','1.2.4','1.20.1','1.3.1'].sortVersions()
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