Rob - 4 months ago 37

Javascript Question

I have a d3 tree based on the following...

http://bl.ocks.org/mbostock/1093025

How would I get a count of all the children? I have tried this however it counts all the rows in the tree...

`$(".tree_badge").text(tree.links(nodes).length);`

So in the example it should count all the children where children would be the orange coloured rows in the tree (like those in cluster, graph, etc).

Thanks for any insight!

Answer

I actually had a similar problem where I had to grab all of the descriptions from a tree below a particular node. The answer in my case and yours is to recursively descend the tree and do something on the way down. Should look something like this.

```
var count;
function count_leaves(node){
if(node.children){
//go through all its children
for(var i = 0; i<node.children.length; i++){
//if the current child in the for loop has children of its own
//call recurse again on it to decend the whole tree
if (node.children[i].children){
count_leaves(node.children[i]);
}
//if not then it is a leaf so we count it
else{
count++;
}
}
}
```

Note: if you want to count all of the nodes below your node and not just the ones at the end of the tree, just add a count++ inside the if as well as the else.

Source (Stackoverflow)

Comments