Search code examples
vis.jsvis.js-network

How to stay only edges between two nodes?


I have follow graph. I need to stay only ages that placed between two nodes Company 5 and Company 7 in my example. Like:

enter image description here

The problem that I can't find any examples how to do it. Could anybody help me?

The live example: https://jsfiddle.net/5ntzqafv/

// create an array with nodes
var nodes = new vis.DataSet([
                {id: 1, label: 'Company 1', group: "company", },
                {id: 2, label: 'Mike', group: "owner"},
                {id: 3, label: 'David', group: "founder"},
                {id: 4, label: 'Company 2', group: "company"},
                {id: 5, label: 'Company 3', group: "company"},
                {id: 6, label: 'Company 4', group: "company"},
                {id: 8, label: 'Company 5', group: "company", borderWidth: 4, color: { border: '#077eb8' }, font: { size: 16},},
                {id: 9, label: 'Company 6', group: "company"},
                {id: 10, label: 'Company 7', group: "company", borderWidth: 4, color: { border: '#077eb8' }, font: { size: 16},},
                {id: 11, label: 'Company 8', group: "company"},
          {id: 12, label: 'Company 9', group: "company"}
]);

// create an array with edges
var edges = new vis.DataSet([
                {from: 1, to: 2},
                {from: 1, to: 3},
                {from: 2, to: 11},
                {from: 3, to: 4},
          {from: 4, to: 3},
                {from: 2, to: 8}, 
                {from: 3, to: 6},
                {from: 3, to: 5},
                {from: 4, to: 9},
          {from: 7, to: 4},
          {from: 7, to: 12},
          {from: 10, to: 12},
          {from: 9, to: 12},
                {from: 4, to: 10}
]);

// create a network
var container = document.getElementById("mynetwork");
var data = {
  nodes: nodes,
  edges: edges
};
var options = {nodes: {
        shape: "box",
        widthConstraint: {
          maximum: 200
        }
      }};
var network = new vis.Network(container, data, options);


Solution

  • You can just use some simple algorithms to search paths in graphs, like BFS.

    Algorithm is described here: https://en.wikipedia.org/wiki/Breadth-first_search

    My implementation: https://jsfiddle.net/alexey_kuldoshin/3svmqujz/74/

    function getPath(graph, from, to) {
        let queue = [ from ];
        let p = {};
        p[from] = -1;
        while (queue.length > 0) {
            let v = queue.shift();
            if (v == to) {
                break;
            }
            graph[v].forEach(edge => {
                if (!(edge in p)) {
                    p[edge] = v;
                    queue.push(edge);
                }
            });
        }
        let ans = [];
        while (to != -1) {
            ans.push(to);
            to = p[to];
        }
        console.log(ans);
        return ans;
    }