Rob Rob - 10 months ago 94
Javascript Question

d3 tree count all children

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

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


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!


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){
        //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){
            //if not then it is a leaf so we count it

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.