As part of my job at Hibob, I’ve been looking for a way to construct an Organizational-Chart out of a list of employees. This article shows one approach to creating an immutable tree structure out of a list of hierarchical objects.

Org-Chart / bob
Our input is a list of employees — each employee entry has an “id” and “managerId” property. The managerId can be empty or reference another employee on the list as its manager.

List ⇒ Tree
I googled my way as a good lazy citizen does and found some efficient ways to do the job.
Basically, all the solutions I’ve found involve creating a “Node” object with an empty children array — then adding children to it on the fly pointing to other nodes. Adding children to a node object means we mutate this object after creation and therefore construct a tree made of mutable objects. This isn’t necessarily bad and depends on one’s needs, but I wanted to explore a way to construct nodes in an Immutable way without sacrificing much efficiency compared to mutable solutions.