fork download
  1. process.stdin.resume();
  2. process.stdin.setEncoding('utf8');
  3.  
  4. process.stdin.on('data', function (chunk) {
  5. const data = JSON.parse(chunk).employees;
  6. const employees = data.map((item) => ({...item, subordinates: []}));
  7.  
  8. const buildHierarchy = (employees, managerId) => {
  9. return employees
  10. .filter(emp => emp.managerId == managerId)
  11. .map(emp => ({...emp, subordinates: buildHierarchy(employees, emp.id)}));
  12. }
  13.  
  14. const result = buildHierarchy(employees, null);
  15.  
  16. process.stdout.write(JSON.stringify(result, null, 2));
  17. });
Success #stdin #stdout 0.09s 36080KB
stdin
{
  "employees": [
    {"id": 1, "name": "Alice", "salary": 5000, "managerId": null},
    {"id": 2, "name": "Bob", "salary": 4000, "managerId": 1},
    {"id": 3, "name": "Charlie", "salary": 3000, "managerId": 1},
    {"id": 4, "name": "David", "salary": 2500, "managerId": 2},
    {"id": 5, "name": "Eve", "salary": 2000, "managerId": 2}
  ]
}
stdout
[
  {
    "id": 1,
    "name": "Alice",
    "salary": 5000,
    "managerId": null,
    "subordinates": [
      {
        "id": 2,
        "name": "Bob",
        "salary": 4000,
        "managerId": 1,
        "subordinates": [
          {
            "id": 4,
            "name": "David",
            "salary": 2500,
            "managerId": 2,
            "subordinates": []
          },
          {
            "id": 5,
            "name": "Eve",
            "salary": 2000,
            "managerId": 2,
            "subordinates": []
          }
        ]
      },
      {
        "id": 3,
        "name": "Charlie",
        "salary": 3000,
        "managerId": 1,
        "subordinates": []
      }
    ]
  }
]