11/12/2024
use a flat array and reference parent-child relationships using an id and parentId system.
OUTPUT:
[
{
id: 1,
name: "Parent 1",
parentId: null,
children: [
{
id: 2,
name: "Child 1",
parentId: 1,
children: [
{ id: 3, name: "Grandchild 1", parentId: 2, children: [] },
{ id: 4, name: "Grandchild 2", parentId: 2, children: [] }
]
},
{
id: 5,
name: "Child 2",
parentId: 1,
children: []
}
]
},
{
id: 6,
name: "Parent 2",
parentId: null,
children: [
{ id: 7, name: "Child 3", parentId: 6, children: [] }
]
}
];
CODE:
function buildTree(flatArray) {
const idToNodeMap = {};
const tree = [];
// Create a map of id to node
flatArray.forEach(item => {
idToNodeMap[item.id] = { ...item, children: [] };
});
// Assign children to their respective parents
flatArray.forEach(item => {
if (item.parentId === null) {
tree.push(idToNodeMap[item.id]);
} else {
idToNodeMap[item.parentId].children.push(idToNodeMap[item.id]);
}
});
return tree;
}
const tree = buildTree(flatHierarchy);
console.log(tree);
const flatHierarchy = [
{ id: 1, name: "Parent 1", parentId: null },
{ id: 2, name: "Child 1", parentId: 1 },
{ id: 3, name: "Grandchild 1", parentId: 2 },
{ id: 4, name: "Grandchild 2", parentId: 2 },
{ id: 5, name: "Child 2", parentId: 1 },
{ id: 6, name: "Parent 2", parentId: null },
{ id: 7, name: "Child 3", parentId: 6 }
];
Traversal Functions for Hierarchical Data
Once you have a hierarchical structure, you can traverse it recursively to search or perform actions.
function findNodeById(tree, id) {
for (const node of tree) {
if (node.id === id) {
return node;
}
if (node.children.length > 0) {
const result = findNodeById(node.children, id);
if (result) {
return result;
}
}
}
return null;
}
const result = findNodeById(tree, 3); // Find node with id 3
console.log(result);