Search code examples
javascriptdata-structuresgraph

Add nodes in a Graph not working perfectly in js


I have created a graph which containing key and value pair ,key is for node number and value for adjacency list value which is an array of adjacent edges, here I wrote a function that will add the node and adjacency edges in the graph, but here the function is not working ,which thing should I have to modified here that I want graph like { 1:[2,4],2:[1,3],3:[2,4],4:[1,4],5:[3,4]} code is given below

var graph = {
    1: [2, 4],
    2: [1, 3],
    3: [2, 4],
    4: [1, 4]
  };
  function addNode(key, value = []) {
    graph[key].push({ value: value });
  }
  addNode(5, [3, 4]);
  console.log(graph);

Solution

  • function addNode(key, value = []) {
      graph[key] = value;
    }
    

    Or, if you want to add new values to the node, given it already existed:

    function addNode(key, values = []) {
      (graph[key] ??= []).push(...values);
    }
    

    Try it:

    var graph = {
      1: [2, 4],
      2: [1, 3],
      3: [2, 4],
      4: [1, 4]
    };
    
    function addNode(key, value = []) {
      graph[key] = value;
    }
    
    function addValuesToNode(key, value = []) {
      (graph[key] ??= []).push(...value);
    }
    
    addNode(5, [3, 4]);
    console.log(graph);
    
    addValuesToNode(5, [1]);
    console.log(graph);