This is certainly possible, but it requires recursion.
The first thing you want to do (as you already found out, actually) is divided into slashes. For simplicity, we will use map :
paths = paths.map(function(path) { return path.split('/'); });
Now we want to convert this to an array of objects with the name and children properties. This means that we have to use recursion.
In this function, we will make the first pass, grouping them by their first element:
var items = []; for(var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; var name = path[0]; var rest = path.slice(1); var item = null; for(var j = 0, m = items.length; j < m; j++) { if(items[j].name === name) { item = items[j]; break; } } if(item === null) { item = {name: name, children: []}; items.push(item); } if(rest.length > 0) { item.children.push(rest); } }
Then we can rewrite all of these (provided that the name of the function we selected was structurize ):
for(i = 0, l = items.length; i < l; i++) { item = items[i]; item.children = structurize(item.children); }
Now we have a good structure. Then we can strengthen it, again using a recursive function. Since the directory list is simply the name of each item, followed by a list of the contents of the subdirectories, we can easily write this:
function stringify(items) { var lines = []; for(var i = 0, l = items.length; i < l; i++) { var item = items[i]; lines.push(item.name); var subLines = stringify(item.children); for(var j = 0, m = subLines.length; j < m; j++) { lines.push(" " + subLines[j]); } } return lines; }
Then, to do this:
console.log(stringify(structurize(paths)).join("\n"));