Stephen S
Stephen S

Reputation: 3994

D3.js - Get all possible child elements for a node

I am using D3.js to create a Tree structure. The application I am developing requires me to show the immediate children & the total children for each node. I can find the immediate children using d.children.length , but is it possible to get the total child elements(upto leaf) below a node ? If yes how can I do it ?

Upvotes: 0

Views: 3321

Answers (1)

Christopher Chiche
Christopher Chiche

Reputation: 15325

You could do this using a recursive function such as:

function getDescendants(node) {
    if(!node.children) {
        return 0;
    }
    var total = 0;
    node.children.forEach(function(d) {
        total += 1+getDescendants(d);
    }) 
    return total;
}

The goal is to go through each node and count it's descendance (including itself).

An alternative method is to use the reduce function in order to write less code.

function getDescendantsReduce(node) {
    if(!node.children) {
        return 0;
    }
    return node.children.reduce(function(c,d) {
        // c is the accumulator, we start with c=0 
        // d is the node of the array that gets computed 
        return c+1+getDescendants(b)
    },0)
}

http://jsfiddle.net/hFTN8/16/


EDIT

In "modern" javascript, the function would be:

const getDescendantsReduce = (node) => node.children
  ? node.children.reduce( (c,b) => c+1+getDescendants(b), 0)
  : 0;

Upvotes: 2

Related Questions