How to create and use graphs
To create a graph, you first need to create a node. A node is a piece of data that contains two parts: the data itself, and a list of edges.
var node = {
data: "Alice",
edges: []
};
Adding Edges to a Graph
To add an edge to a graph, you need to add the edge to the edges
list of the node.
node.edges.push({
to: "Bob"
});
Traversing a Graph
To traverse a graph, you need to start at a node and then follow the edges
list of each node until you reach the end of the graph.
var currentNode = node;
while (currentNode != null) {
document.write(currentNode.data);
currentNode = currentNode.edges[0].to;
}
Examples
Graphs can be used to represent social networks, routing problems, or anything else that can be represented as a set of nodes and edges.
Here is an example of how to create and use a graph in JavaScript:
var graph = new Graph();
// Create nodes
var node1 = {
data: "Alice"
};
var node2 = {
data: "Bob"
};
var node3 = {
data: "Carol"
};
// Add edges
graph.addEdge(node1, node2);
graph.addEdge(node1, node3);
// Traverse the graph
var currentNode = node1;
while (currentNode != null) {
document.write(currentNode.data);
currentNode = currentNode.edges[0].to;
}
This code creates a graph with the following structure:
Alice
├── Bob
└── Carol
The code then traverses the graph, printing out the data of each node.
Try to run code by using of Front-end Editor by clicking the button Try Our Frontend Editor (HTML/CSS/JS) below.