task1
const getTree = (flatArray) => { const map = new Map(); const tree = []; for (const node of flatArray) { map.set(node.id, { ...node, child: [] }); } for (const node of flatArray) { const { id, parentId } = node; if (parentId === null || parentId === undefined) { tree.push(map.get(id)); } else { const parent = map.get(parentId); if (parent) { parent.child.push(map.get(id)); } } } return tree; }; const flatArray = [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3, parentId: 1 }, { id: 4, parentId: 2 }, { id: 5, parentId: 2 }, { id: 6, parentId: null }, { id: 7, parentId: 6 }, ]; const tree = getTree(flatArray); console.log(JSON.stringify(tree, null, 2));
Leave a Comment