Notebooks 2.0 is here.

Public
Edited
Nov 22, 2022
1 star
Insert cell
Insert cell
Insert cell
Insert cell
function prune(node, root) {
// copy the root so that it stays intact
// docs say that .copy() will retain reference to original data
// which is actually quite convenient in this case as long as we are aware
var clipped = root.copy();
// now let's find the node in our copied hierarchy
// to avoid accidentally changing our original root
// we can match on data since reference will be the same
var nodecopy = clipped.descendants().filter(d => d.data === node.data)[0];
// find the path from root to our node
// since this is all we will want to keep
var path = clipped.path(nodecopy);
path.forEach( (d,i) => {
if( path[i+1] ) { // if there is a subsequent path then assign subsequent as children
d.children = [path[i+1]]; // children should be an array
if(path[i+1].hasOwnProperty("children")) {
// this assumes we want the hierarchy to end with node
// remove if this is not the desired behavior
delete path[i+1].children;
}
}
});

return clipped;
}
Insert cell
Insert cell
Insert cell
d3.version

Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more