Hi, I had an interview this week and have been still struggling trying to figure out the solution for this. I know that a recursive approach will work, but I can't seem to get the logic to print it correctly. I've even gotten to a point where the names will print, but not in the correct format. I have since then went back on the code and tried something new (Which still doesnt work). Any guidance or help would be greatly appreactied.
The names shall be printed in order of heirarchy and nested under their manager. Alice is the top manager with the id of 8. Bob and Emp7 are nested under Alice as their managerId is 8 and Alice's id is 8. Hope this makes sense.
/// Pretty print org chart
// Alice
// Bob
// Emp3
// Emp4
// Emp5
// Emp6
// Emp7
const EMPLOYEES = [
{ id: 8, managerId: 8, name: "Alice" },
{ id: 2, managerId: 8, name: "Bob" },
{ id: 3, managerId: 2, name: "Emp3" },
{ id: 4, managerId: 3, name: "Emp4" },
{ id: 5, managerId: 4, name: "Emp5" },
{ id: 6, managerId: 3, name: "Emp6" },
{ id: 7, managerId: 8, name: "Emp7" },
];
function prettyPrintOrg(employees) {
let empMap = {}, maxId = 0;
var prettyNames = '';
for (var emp of employees) {
if (empMap[emp.id] === undefined) {
empMap[emp.id] = {"name": emp.name, reports: []};
maxId = Math.max(maxId, emp.id);
}
if (empMap[emp.managerId] && emp.id !== emp.managerId) {
empMap[emp.managerId].reports.push(emp.id);
}
}
function printNames(empMap, maxId) {
let curId = empMap[maxId];
prettyNames += ' ' + curId.name + '\n';
while (curId.reports) {
console.log(curId.reports.shift())
/* printNames(empMap, curId.reports.shift()); */
}
console.log(prettyNames);
}
printNames(empMap, maxId);
return prettyNames;
}
prettyPrintOrg(EMPLOYEES)