Complex D3 Nest Manipulation
CSS
path, circle{stroke:black; fill:none;}
JavaScript
var arrays = [[1,2,3,4,5],
[1,2,6,4,5],
[1,3,6,4,5],
[1,2,3,6,5],
[1,7,5],
[1,7,3,5]];
//Each array describes a path from the root
//to a unique leaf, via named labels (here integers)
var root={},
path, node, next, i,j, N, M;
for (i = 0, N=arrays.length; i<N; i++){
//for each path in the data array
path = arrays[i];
node = root; //start the path from the root
for (j=0,M=path.length; j<M; j++){
//follow the path through the tree
//creating new nodes as necessary
if (!node.children){
//undefined, so create it:
node.children = {};
//children is defined as an object
//(not array) to allow named keys
}
next = node.children[path[j]];
//find the child node whose key matches
//the label of this step in the path
if (!next) {
//undefined, so create
next = node.children[path[j]] =
{label:path[j]};
}
node = next;
// step down the tree before analyzing the
// next step in the path.
}
}
root = d3.values(root.children)[0];
//console.log(root);
//recurse through the tree, turning the child
//objects into arrays
function childrenToArray(n){
if (n.children) {
//this node has children
n.children = d3.values(n.children);
//convert to array
n.children.forEach(childrenToArray);
}
}
childrenToArray(root);
console.log(root);
d3.select("body").text(JSON.stringify(root, null, '\t'));
//(Graphing code from http://bl.ocks.org/mbostock/4063570 )
var height=500, width = 600;
var cluster = d3.layout.cluster()
.size([height, width - 100])
/* .children(function children(d) {
//get children as an array:
return d3.values(d.children);
//you could add in a sort if you wanted
//the nodes returned...