Public
Edited
May 1, 2020
Insert cell
Insert cell
Insert cell
Insert cell
treeToMatrix(smallTree)
Insert cell
matrixToTree([
[["i-0", 3793],["B", 0]],
[["i-0", 3793],["i-1", 3414],["D", 0]],
[["i-0", 3793],["i-1", 3414],["i-2", 3340],["F", 0]],
[["i-0", 3793],["i-1", 3414],["i-2", 3340],["i-3", 2969],["H", 0]],
[["i-0", 3793],["i-1", 3414],["i-2", 3340],["i-3", 2969],["I", 0]]
])
Insert cell
treeToMatrix = (tree) => {
const convert = (node, prev, i) => {
if(isLeaf(node)) {
return [[...prev, node.name],1];
}
const curr = [...prev, `i-${i}`];
let maxIndex = i;
const children = [];
node.children.forEach((child) => {
const [c, k] = convert(child, curr, maxIndex);
children.push(c);
maxIndex += k;
})
let result = [];
children.forEach((child) => {
if(Array.isArray(child) && Array.isArray(child[0])) {
result = [...result, ...child];
} else {
result.push(child);
}
})
return [result, maxIndex];
};
return convert(tree, [], 0)[0];
}
Insert cell
matrixToTree = (inputMatrix) => {
const group = (matrix, level) => {
return matrix.reduce((a, h) => {
if(h[level] && a.hasOwnProperty(h[level][0])) {
a[h[level][0]].push([h, h[level][1]]);
} else {
a[h[level][0]] = [ [h, h[level][1]] ];
}
return a;
}, {});
};
const convert = (matrix, level) => {
const curr = group(matrix, level);
return Object.entries(curr).map(([k, v]) => {
console.log(v);
if(v.length === 1) {
return { name: k, dist: v[0][1] }
} else {
return { name: k, dist: v[0][1], children: convert(v.map(vv => vv[0]), level+1) }
}
});
};
return { name: "root", children: convert(inputMatrix, 0) };
}
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more