Search code examples
angulartypescriptlogic

Sort Nodes for a graph in the correct order


I'm working on a graph and I have difficulties with the correct sorting/rendering of the graph nodes in the right order.

For the logic, I'm using Typescript within an Angular app.

I have an array with links, where source node and target node are specified for each data set.

linksArray = [{source: 'NodeId1', target: 'NodeId3'}, {source: 'NodeId1', target: 'NodeId6'}, {source: 'NodeId6', target: 'NodeId2'}, {source: 'NodeId8', target: 'NodeId10'}...]

Now I want to iterate this array and call "graph.add(node)" for each entry in the correct order.

The algorithm is something like this:

  1. Take the first source node & target node and directly add them both to the graph (The first entry (linksArray[0]) is always the first node. I can be sure about that.).
  2. Check the array to see if the target node occurs again as a source node. Add the target-node of the previous source next - REPEAT, etc.
  3. The goal is to render the graph in the right node order & next to each other.

Otherwise, some nodes would be far apart. And that would not be readable.

Maybe I'm wrong in my thinking and it's much simpler.

Thanks in advance.


Solution

  • I solved it myself.

    NodesArray contains the individual nodes in the correct order in which they are to be rendered.

      let nodesArray: any[] = [];
    
      let nodeLinks = [{source: 'NodeId1', target: 'NodeId3'}, {source: 'NodeId1', target: 'NodeId6'}, {source: 'NodeId6', target: 'NodeId2'}, {source: 'NodeId8', target: 'NodeId10'}];
    
      let tempTargetNode: string;
     
      // Sort Nodes
    
      nodeLinks.forEach((firstLevelLink: { source: any; target: any }, index: number) => {
    
        if (index === 0) {
    
          nodesArray.push({ id: firstLevelLink.source, name: firstLevelLink.source });
    
          nodesArray.push({ id: firstLevelLink.target, name: firstLevelLink.target });
    
          tempTargetNode = firstLevelLink.target;
    
        } else {
    
          nodeLinks.forEach((secondLevelNodeLink: { source: any; target: any }, index: number) => {
    
            if (tempTargetNode === secondLevelNodeLink.source) {
    
              nodesArray.push({ id: secondLevelNodeLink.target, name: secondLevelNodeLink.target });
    
              tempTargetNode = secondLevelNodeLink.target;
    
            }
    
          });
    
        }
    
      });