How to Create Graphs in JavaScript

Learn and implement adjacency list representation for graphs in JavaScript.


To start the project, we'll create a weighted undirected graph, in which the weight of each edge between two cities will represent the travel time to reach from one city to the other city. We'll implement the code to create this graph using adjacency list representation. In this technique, we store the graph in an array (say A), whose each element is also an array. Each element of the arrayAiA_{i}​ is a list that contains all the vertices that are adjacent to vertex i. While creating a weighted graph, the weight associated with each edge will be stored along with the vertex in the list. Each element in the list will be of size two, where the first element will denote the vertex and the other element will denote the weight for that edge. In an undirected graph, if vertex j is in the list AiA_{i}, then vertex i will be in the list AjA_{j}.

Adjacency list representation

Let's visualize what adjacency list representation is using some illustrations. Below is a weighted undirected graph:

Get hands-on with 1200+ tech skills courses.