- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a Graph in Javascript
We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy.
An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges.
Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph.
We'll initially define the following methods −
- addNode: Adds a node to the graph
- addEdge: Adds an undirected edge to the graph
- addDirectedEdge: Adds a directed edge
Example
class Graph { constructor() { this.edges = {}; this.nodes = []; } addNode(node) { this.nodes.push(node); this.edges[node] = []; } addEdge(node1, node2) { this.edges[node1].push(node2); this.edges[node2].push(node1); } addDirectedEdge(node1, node2) { this.edges[node1].push(node2); } display() { let graph = ""; this.nodes.forEach(node => { graph += node + "->" + this.edges[node].join(", ") + "
"; }); console.log(graph); } }
You can test these methods and our class using −
Example
let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addNode("E"); g.addEdge("A", "C"); g.addEdge("A", "B"); g.addDirectedEdge("A", "D"); g.addEdge("D", "E"); g.display();
Output
This will give the output −
A->C, B, D B->A C->A D->E E->D
- Related Articles
- Creating a Stack in Javascript
- Creating a Queue in Javascript
- Creating a graph with date and time in axis labels with Matplotlib
- Creating a Set using Javascript
- Creating a BinaryTree using Javascript
- Creating a chained operation class in JavaScript
- Creating a Priority Queue using Javascript
- Creating a linked list using Javascript
- Creating a hash table using Javascript
- JavaScript - Creating a Custom Image Slider
- Creating multiple boxplots on the same graph from a dictionary, using Matplotlib
- Graph Traversals in Javascript
- Creating Arrays using Javascript
- Creating Dictionary using Javascript
- Creating a Doubly Linked List using Javascript

Advertisements