// 方法一 前位补0排序
var sort1 = function(){
var vs = ['1.2.0','1.12.1','0.1','2.2','2.3.4','3.1.1.1.1.1','2','11.2.1','0','100'];
var zeroLen = 10;
var vsSplit = vs.map(function(one){
var sp = one.split('.');
return sp.map(function(t){
var s = '';
for(var i=0;i<zeroLen - t.length;i++){
s ='\0'+ s;
}
return s + t;
}).join('.');
});
return vsSplit.sort(function(a,b){
return (a>b?1:-1);
}).map(function(one){
return one.replace(/\0/g,'');
});
}
console.log(JSON.stringify(sort1()));
//树+DFS
var sort2 = function(){
var vs = ['1.2.0','1.12.1','0.1','2.2','2.3.4','3.1.1.1.1.1','2','11.2.1','0','100'];
var m = {};
vs.map(function(one){
var p = m;
one.split('.').map(function(a){
p[a] = p[a] || {};
p = p[a];
});
p.last = true;
})
// console.log(JSON.stringify(m));
var l = [];
var dfs = function(p,t,d){
if(p.last){
l.push(t.join('.'));
}
for(var k in p){
if(k!='last'){
t[d]=k;
var _t = t.slice(0,d+1);
// console.log(_t);
dfs(p[k],_t,d+1);
}
}
}
dfs(m,[],0);
return l;
}
console.log(JSON.stringify(sort2()));
// 方法三 按列比较
var sort3 = function(){
var vs = ['1.2.0','1.12.1','0.1','2.2','2.3.4','3.1.1.1.1.1','2','11.2.1','0','100'];
var vsq = vs.map(function(one){
return one.split('.');
});
return vsq.sort(function(a,b){
var l = a.length < b.length ? a.length : b.length;
for(var i = 0;i<l;i++){
if(a[i]*1 != b[i] * 1){
return a[i]*1 > b[i]*1 ? 1: -1;
}
}
return a.length > b.length ? 1 : -1;
}).map(function(t){
return t.join('.');
});
}
console.log(JSON.stringify(sort3()));