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:
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!




