0

How do I make sure that when I'm pushing a new node that, if it is already there then it would not be pushed, otherwise push it.

function defineGraph(edges){
  // Define the graph
  var graph = { nodes: Object.create(null) };

  // Define nodes and edges
  graph.nodes = []
  graph.edges = []

  // Add content to graph.nodes and graph.edges
  edges.forEach(function (edge) {
    var [f, labels, t, att] = edge;
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []})

    graph.edges.push([f, t, [labels]])
  });

  return graph; }

If, it should be of any help my output format is JSON. For example,

"nodes": [
  {
     "label": "a",
     "attributes": [
        "initial"
     ]
  }, {...}
Stiiq
  • 47
  • 1
  • 1
  • 7

2 Answers2

0

Maybe something like this:

Is it possible to define nodes and edges as Objects and not arrays? If so, you can check against the object's properties:

graph.nodes = {};

// Assuming you index your nodes by, ie, attr
if (typeof graph.nodes.attr === 'undefined') {
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []})
}

If nodes need to be an array, then you should check for the index's index. This solution is more expensive:

graph.nodes = [];

if (graph.nodes.indexOf(attr) === -1) {
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []}
}
Mauricio Machado
  • 613
  • 1
  • 5
  • 14
0

You can deepcheck the object before pushing into array. You can use lodash library for this.

const isEqual = _.isEqual({a: 'b', y:'z'}, {a: 'b', y:'z'})
// here isEqual will be true.

You can apply this in your code as below,

edges.forEach(edge => {
  const [f, labels, t, att] = edge;

  const node1 = {label: f, attribute: att};
  if (!graph.nodes.find(n => _.isEqual(n, node1) {
    graph.nodes.push(node1);
  }

  const node2 = {label: t, attributes: []};
  if (!graph.nodes.find(n => _.isEqual(n, node2) {
    graph.nodes.push(node2);
  }

  const edge1 = [f, t, [labels]];
  if (graph.edges.find(e => _.isEqual(e, edge1) {
    graph.edges.push(edge1);
  }
});