Reputation: 3994
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
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)
}
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