I got a problem to convert multiple full path to a path tree, like this:
/* source:
/a/b/c/d/e
/a/b/e/f/g
/a/b/h
/a/i/j
/a/i/k
what I need:
a
/ \
b i
/|\ / \
c e h j k
| |
d f
| |
e g
*/
So I have to scan each full-path to generate this tree structure, here is my code with JavaScript:
let rtree = [];
array.map((item) =>{
let {key,title}=item; // key is the full path
let uri=key.split('/'); // split the full path with '/'
let uri_pt = rtree;
let path='';
if(uri_pt.length==0){
let root={
key:path+'/'+uri[1],
title:uri[1],
}
if(uri.length>2){
root.children=[];
}
uri_pt.push(root);
}
for (let i in uri){
if(i==0) continue;
path+='/'+uri[i];
let treeitem = {
key:path,
title:uri[i]
}
if(i!=uri.length-1){
treeitem.children=[];
}
if(uri_pt.length==0){
uri_pt.push(treeitem);
}
let isExist=false;
for(let j in uri_pt){
if(uri_pt[j].key==treeitem.key){
if(i!=uri.length-1 && !uri_pt[j].children){
uri_pt[j].children=[];
}
uri_pt=(i==uri.length-1?uri_pt:uri_pt[j].children);
isExist=true;
break;
}
}
if (!isExist){
uri_pt.push(treeitem);
if(i!=uri.length-1 && !uri_pt[uri_pt.length-1].children){
uri_pt[uri_pt.length-1].children=[];
}
uri_pt=(i==uri.length-1?uri_pt:uri_pt[uri_pt.length-1].children);
}
}
})
It's a totally inefficiency algorithm, but worked, if any improvement, please let me know.