D3.js node.path() Function
The node.path() function in d3.js is used return the shortest path between the source and destination node.
Syntax:
node.path(target);
Parameters: This function accepts single parameter as given above and described below:
- target: This parameter accepts a destination node.
Return Value: This function return an array.
Below given are a few examples of the function given above.
Example 1: Path from root node to any other node.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta name = "viewport" path1tent =
"width=device-width, initial-scale = 1.0" />
< script src =
</ script >
</ head >
< body >
< script >
// Constructing a tree
var tree = {
name: "rootNode",
children: [
{
name: "child1"
},
{
name: "child2",
children: [
{
name: "grandchild1",
children: [
{ name: "grand granchild1" },
{ name: "grand granchild2" }
]
},
]
},
{
name: "child3",
children: [
{ name: "grandchild2" },
{ name: "grandchild3" },
{ name: "grandchild4" },
{ name: "grandchild5" }
]
}
]
};
var obj = d3.hierarchy(tree);
// Printing path from rootnode
// to grand granchild1
console.log(obj.path(obj.children[1].
children[0].children[0]));
console.log("Printing path from rootnode"
+ "to grand granchild1: ");
let path = obj.path(obj.children[1]
.children[0].children[0]);
console.log(path[0].data.name + "->"
+ path[1].data.name + "->"
+ path[2].data.name + "->"
+ path[3].data.name);
</ script >
</ body >
</ html >
|
Output:
Example 2: The following code demonstrates path from any node to any other node.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta name = "viewport" path1tent =
"width=device-width, initial-scale = 1.0" />
< script src =
</ script >
</ head >
< body >
< script >
// Constructing a tree
var tree = {
name: "rootNode",
children: [
{
name: "child1"
},
{
name: "child2",
children: [
{
name: "grandchild1",
children: [
{ name: "grand granchild1" },
{ name: "grand granchild2" }
]
},
]
},
{
name: "child3",
children: [
{ name: "grandchild2" },
{ name: "grandchild3" },
{ name: "grandchild4" },
{ name: "grandchild5" }
]
}
]
};
var obj = d3.hierarchy(tree);
// Printing path from any node to
// any other node
var grandchild3 = obj.children[2].children[1];
var child2 = obj.children[1];
console.log(grandchild3.path(child2));
console.log("Printing path from anynode to"
+ " any other node ");
let path = grandchild3.path(child2);
console.log(path[0].data.name + "->"
+ path[1].data.name + "->"
+ path[2].data.name + "->"
+ path[3].data.name);
</ script >
</ body >
</ html >
|
Output:
Last Updated :
23 Sep, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...