I have a function buildTree that takes as an input json data and visualize them using d3.js with cola.js. The idea is that i click a button and add a json to d3. Then by clicking another button i add another js and keep the old one so i end up with two trees. In my example i have a node that exists in both json files so i want to end up with these two trees connected and the node appears one time.
I managed to get the existing tree, add new one, delete the node that exists two times and update the links but one link never connects to the coexisting node.
The JSON files have the following format:
{
"nodes": [
{"id": "a", "name": "a", "type": "tool", "width": 60, "height": 40},
{"id": "b", "name": "b", "type": "tool", "width": 60, "height": 40},
{"id": "c", "name": "c", "type": "tool", "width": 60, "height": 40}
],
"links": [
{"source": 0, "target": 1},
{"source": 0, "target": 2}
],
"groups": []
}
And the second one:
{
"nodes": [
{"id": "h", "name": "h", "type": "tool", "width": 60, "height": 40},
{"id": "i", "name": "i", "type": "tool", "width": 60, "height": 40},
{"id": "c", "name": "c", "type": "tool", "width": 60, "height": 40}
],
"links": [
{"source": 0, "target": 1},
{"source": 0, "target": 2}
],
"groups": []
}
So c is a node that exists in both JSON files and should appear in the tree only once but with both links.
And the buildTree is something like:
function buildTree(jsonSource) {
d3.json(jsonSource, function (error, graph) {
//get existing data if any and merge them with new data
myNodes = svg.selectAll(".node");
myLinks = svg.selectAll(".link");
//update the existing nodes with the new ones, remove duplications and store them in removedNodes
allNodes = graph.nodes.concat(myNodes.data());
var uniqueIds = [];
var allNodesUnique = [];
var removedNodes = [];
for (var i = 0; i < allNodes.length; i++) {
var id = allNodes[i].id;
if (uniqueIds.indexOf(id) == -1) {
uniqueIds.push(id);
allNodesUnique.push(allNodes[i]);
} else {
removedNodes.push(allNodes[i]);
}
}
allNodes = allNodesUnique;
//update links
allLinks = graph.links.concat(myLinks.data());
d3.selectAll("svg > *").remove();
cola
.nodes(allNodes)
.links(allLinks)
.groups(graph.groups)
.start();
...