title: JavaScript - build a tree data structure recursively
body: <p>I have a function called tree, which takes array of objects (as data fields from a database) and array of strings for keys. The function loops through rowsArray and recursively creates object with nested properties based on keyArray.</p>
  
  <pre><code>const tree = (rowsArray, keysArray) =&gt; {
    return rows.reduce((acc, row) =&gt; {
      const groupBy = (row, keys,) =&gt; {
        const [first, ...rest] = keys;
  
        if (!first) return [row];
  
        return {
          [row[first]]: groupBy(row, rest),
        }
      };
      acc = {...groupBy(row, keys), ...acc};
      return acc;
    }, {});
  }
  </code></pre>
  
  <p>The data is following:</p>
  
  <pre><code>const data = [{
          ID: 1,
          Main: "Financial",
          Sub: "Forecasts",
          Detail: "General"
      }, {
          ID: 2,
          Main: "Financial",
          Sub: "HR",
          Detail: "Headcount"
  }];
  
  const result1 = tree(data, ["Main", "Sub", "Detail"]);
  console.log(result1); 
  </code></pre>
  
  <p>When I log the result, I get:</p>
  
  <pre><code>/*
  // actual output
    { 
      Financial: { 
        Forecasts:  { 
          General: [Array] 
        } 
      } 
    }
  </code></pre>
  
  <p>Whereas, I would like to get following:</p>
  
  <pre><code>  // expected
    { 
      Financial: { 
        Forecasts:  { 
          General: [Array] 
        },
        HR:  { 
          Headcount: [Array] 
        }
      } 
    }
    */
  </code></pre>
  
  <p>The problem is, that acc variable in main function gets overridden and I get new object, instead of accumulative and I am not quite sure how to recursively build this object. I tried to pass instances of acc to groupBy function (to remember previous results), but no luck.</p>
  
  <p>Do you have any idea how I could rewrite tree function or groupBy function to accomplish my goal? Thanks!</p>