I am working with trees in D3 and so far it has been a lot of fun.
Given a user clicks on an inner node (circle), I would like to
- provide a list of all leaf names
- color all paths from that node leading to the leaves.
Here is some code I have written for that purpose
var circles = nodeEnter.append("svg:circle")
.attr("r", function(d){ return d.children ? 5 : 0; })
.on("click", get_all_children);
function get_all_children(d){
var all_children = get_all_childs(d);
console.log("end, our array has: "+all_children.length+" elements");
all_children.forEach(function(elem){
console.log(elem.name);
});
}
function get_all_childs(d, all_childs){
var all_children = new Array;
all_children.push(all_childs);
if(d.children){
var children = d.children;
for (var i = 0; i < children.length; i++) {
var temp_array = get_all_childs(children[i], all_children);
console.log("got from recursion: : "+temp_array.length+" children");
all_children.push(temp_array);
}
}
else{
//return all_children;
//console.log("end, our array has: "+all_children.length+" elements");
}
return all_children;
}
Looks like my recursions are not working correctly.
Can you help me with that?
Try moving var all_children = new Array; outside the scope of the get_all_childs() function. With that variable being redeclared as a new Array on each call of that function, you’ll only ever end up with the results from the final call of that function.
Whereas, if that variable exists outside the scope of that function, as the code recurses, the values pushed onto that array will persist through multiple calls to the function.