Graph data Structure in Javascript

Graphs are a non-hierarchical data structure that consists of nodes and edges. Each node can have one or more edges, and each edge can connect to any other node in the graph.

Example One

class Node {
  constructor(value) {
    this.value = value;
    this.neighbors = [];
  }
}

class Graph {
  constructor() {
    this.nodes = [];
  }

  addNode(node) {
    this.nodes.push(node);
  }

  addEdge(node1, node2) {
    node1.neighbors.push(node2);
    node2.neighbors.push(node1);
  }

  print() {
    for (const node of this.nodes) {
      console.log(node.value);
      for (const neighbor of node.neighbors) {
        console.log(`  ${neighbor.value}`);
      }
    }
  }
}

const graph = new Graph();

const node1 = new Node(1);
const node2 = new Node(2);
const node3 = new Node(3);
const node4 = new Node(4);
const node5 = new Node(5);

graph.addNode(node1);
graph.addNode(node2);
graph.addNode(node3);
graph.addNode(node4);
graph.addNode(node5);

graph.addEdge(node1, node2);
graph.addEdge(node1, node3);
graph.addEdge(node2, node4);
graph.addEdge(node3, node4);
graph.addEdge(node4, node5);

graph.print();

// 1
//   2
//   3
// 2
//   1
//   4
// 3
//   1
//   4
// 4
//   2
//   3
//   5
// 5
//   4

Example Two

class Graph {
  constructor() {
    this.nodes = new Map();
  }

  addNode(node) {
    this.nodes.set(node, []);
  }

  addEdge(node1, node2) {
    this.nodes.get(node1).push(node2);
    this.nodes.get(node2).push(node1);
  }

  getNeighbors(node) {
    return this.nodes.get(node);
  }
}

// Create a graph
const graph = new Graph();

// Add nodes
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addNode('D');

// Add edges
graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
graph.addEdge('B', 'D');

// Get neighbors of a node
console.log(graph.getNeighbors('A')); // Returns ['B', 'C']
console.log(graph.getNeighbors('D')); // Returns ['B']

Read More Topics

System Design Syllabus

Introduction to System Design

Architectural Patterns in System Design

Scalability and Performance in System Design

Database Design in System Design

Distributed Systems in System Design

System Integration and APIs in System Design

Cloud Computing in Sestem Design

Containerization and Orchestration in System Design

High Availability and Disaster Recovery

Security in System Design

Performance Tuning and Optimization

Case Studies and Real-World Projects

B.Tech 4 YEAR CS/IT PROJECTS And Placement

Face Detection Project Idea

Weather Forecasting APP in MERN Project

JavaScript Tips and Trick

Arrays in data Structure

All DSA Topics in JavaScript

e-commerce website React.js logic code

JavaScript function that could be used to add a product to the shopping cart

Linked List in JavaScript

Stack in JavaScript

Trees data Structures in Javascript

Leave a Comment

Skip to content