Skip to content Skip to sidebar Skip to footer

D3 Tree Count All Children

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

Solution 1:

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 childrenfor(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.

Solution 2:

Just use the leaves method

enter image description here

Since I've come here from google looking for how to optimally count each children's descendants, the solution would be

enter image description here

Post a Comment for "D3 Tree Count All Children"