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:
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.
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;
}
});
}
});