Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading