0

someone asked me this js problem

///Employees are displayed with title, first initial, and last name.
// Employees are listed beneath their manager, sorted alphabetically by last name.
// Each Employee is indented by one dash more than their manager.

//Input
const users = [
    { "name": "Celena Ridge", "id": 4, "title": "V.P. People", "manager_id": 1 },
    { "name": "Jessie Rexford", "id": 7, "title": "Engineering Lead", "manager_id": 2 },
    { "name": "Katy Eubank", "id": 2, "title": "CTO", "manager_id": 1 },
    { "name": "Marita Beirne", "id": 1, "title": "CEO" },
    { "name": "Sheba Buchta", "id": 8, "title": "Engineering Lead", "manager_id": 2 }
]

// Output

//- CEO: M. Beirne
// -- CTO: K. Eubank
// --- Engineering Lead: S. Buchta
// --- Engineering Lead: J. Rexford
// -- V.P. People: C. Ridge8*?/

My Solution:

const users = [
    { "name": "Celena Ridge", "id": 4, "title": "V.P. People", "manager_id": 1 },
    { "name": "Jessie Rexford", "id": 7, "title": "Engineering Lead", "manager_id": 2 },
    { "name": "Katy Eubank", "id": 2, "title": "CTO", "manager_id": 1 },
    { "name": "Marita Beirne", "id": 1, "title": "CEO" },
    { "name": "Sheba Buchta", "id": 8, "title": "Engineering Lead", "manager_id": 2 }
];
let result = [];
    function PrintIt(obj) {
        let sub = users.filter(x => x.manager_id === obj.id);
        if (sub.length !== 0) {
            result.push(obj.title + ':' + obj.name);
            sub.forEach((x, i) => {
                PrintIt(x);
            });
        }
        else {
            return result.push(obj.title + ':' + obj.name);
        }
    }

    PrintIt(users.find(x => x.manager_id === undefined));
    console.log(result);

the problem is that, as it is recursive so timeComplexcity is too high. As I am using forEach loop inside the recursive function. what is the best way? although, my solution works just fine.

Akash
  • 848
  • 1
  • 11
  • 30
  • 1
    _my solution works just fine_; does it though? You're not printing the dashes. – Aioros May 04 '20 at 21:20
  • Seems essentially like a duplicate of https://stackoverflow.com/questions/444296/how-to-efficiently-build-a-tree-from-a-flat-structure. – Roope May 04 '20 at 22:07

0 Answers0