Public
Edited
Apr 21, 2023
Insert cell
Insert cell
Insert cell
data = {
const arr = [
{ name: "A", connectsTo: ["B", "C", "L"] },
{ name: "B", connectsTo: ["C", "D", "M"] },
{ name: "C", connectsTo: ["D", "E", "A", "B", "N"] },
{ name: "D", connectsTo: ["E", "F", "B"] },
{ name: "E", connectsTo: ["A", "B", "C", "D", "F", "G"] },
{ name: "F", connectsTo: ["D", "E", "G"] },
{ name: "G", connectsTo: ["B", "C"] },
{ name: "L", connectsTo: ["M", "W"] },
{ name: "M", connectsTo: [] },
{ name: "N", connectsTo: [] },
]
return new Map(arr.map(d => [d.name, d]))
}
Insert cell
JSON.stringify(getRoot("E"), null, 2)
Insert cell
getRoot = (source) => {
const node = data.get(source);
const root = {};
const visited = new Map();

if (node) {
root.name = node.name;
visited.set(root.name, true);

if (node.connectsTo) {
root.children = node.connectsTo.map((d) => {
visited.set(d, true);
return {
name: d,
children: []
};
});

root.children.forEach((d) => {
const n = data.get(d.name);

if (n) {
d.children = n.connectsTo
.filter((m) => {
return (
m !== source &&
m !== d.name &&
!visited.get(m)
);
})
.map((m) => {
visited.set(m, true)
return {
name: m
};
});
}
});
}
}

return root;
}
Insert cell
root = d3.hierarchy(getRoot("A"))
Insert cell
getRoot("A")
Insert cell
mutable source = "E"
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more