Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is how I would write it. Please note that the Big-O bounds for this significantly larger than the answer posted by Onchie (and is roughly <code>O(n^2)</code> vs <code>O(n)</code>). However, for smaller data-sets this is inconsequential and I find this approach easier to follow.</p> <p>First I would have a simple function that, for any manager, tells me who the immediate employees are. (Note that this is <em>just</em> a standard <code>filter</code> function and both <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow">ECMAScript 5</a> and <a href="http://api.jquery.com/jQuery.grep/" rel="nofollow">jQuery</a> provide higher-order functions to do this with cleaner and more succient code.)</p> <pre><code>function employeesForManager(employees, managerName) { var res = [] for (var i = 0; i &lt; employees.length; i++) { if (employees[i].manager == managerName) { res.push(employees[i]) } } return res } </code></pre> <p>Then I would create a recursive function that walks the tree and builds each level. (Likewise, the loop here could be replaced with a simple <code>map</code> function.)</p> <pre><code>function giveShape(employees, manager) { var immediateEmployees = employeesForManager(employees, manager.name) var children = [] for (var i = 0; i &lt; immediateEmployees.length; i++) { children.push(giveShape(employees, immediateEmployees[i])) } // create a new object to avoid mutating original data return { name: manager.name, title: manager.title, children: children } } </code></pre> <p>And all of this is called:</p> <pre><code>var employees= [ {name:"Jeff",manager:null,title:"The Pres"}, {name:"Amy",manager:"Aaron",title:"lll"}, {name:"Chris",manager:"Aaron",title:"lll"}, {name:"Dana",manager:"Aaron",title:"lll"}, {name:"Joe",manager:"Aaron",title:"lll"}, {name:"Mike",manager:"Aaron",title:"lll"}, {name:"Aaron",manager:"Jeff",title:"lll"} ] topManager = employeesForManager(employees, null)[0] result = giveShape(employees, topManager) console.log(result) </code></pre> <p><a href="http://jsfiddle.net/5jLwh/" rel="nofollow">Here is the jsfiddle</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload