Public
Edited
Feb 14, 2020
1 fork
Insert cell
Insert cell
Insert cell
Insert cell
treeToMatrix(smallTree)
Insert cell
{
console.log(JSON.stringify(matrixToTree([
["i-0", "i-0", "i-0", "i-0", "4-1"],
["i-0", "i-0", "i-0", "i-0", "4-2"],
["i-0", "i-4", "i-4", "i-11", "4-8"],
["i-0", "i-4", "i-29", "3-5"]
])))
}
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(a.hasOwnProperty(h[level])) {
a[h[level]].push(h);
} else {
a[h[level]] = [ h ];
}
return a;
}, {});
};
const convert = (matrix, level) => {
const curr = group(matrix, level);
return Object.entries(curr).map(([k, v]) => {
if(v.length === 1) {
return { name: k }
} else {
return { name: k, children: convert(v, level+1) }
}
});
};
return { name: "root", children: convert(inputMatrix, 0) };
}
Insert cell
Insert cell
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