title: Group and aggregate array of objects by key names
body: <p>I would like to write a function in JS that takes lists of names as arguments and is able to group by and aggregate by the specified column names. For example, my data might look like: </p>
  
  <pre class="lang-js prettyprint-override"><code>const SALES = [
    { lead: 'Mgr 1', revenue: 49.99, repName: 'Rep 1', forecast: 81.00 },
    { lead: 'Mgr 1', revenue: 9.99, repName: 'Rep 1', forecast: 91.00 },
    { lead: 'Mgr 1', revenue: 9.99, repName: 'Rep 13', forecast: 82.00 },
    { lead: 'Mgr 2', revenue: 99.99, repName: 'Rep 3', forecast: 101.00 },
    { lead: 'Mgr 2', revenue: 9.99, repName: 'Rep 5', forecast: 89.00 },
    { lead: 'Mgr 3', revenue: 199.99, repName: 'Rep 6', forecast: 77.00 }
  ];
  </code></pre>
  
  <p>I can group and aggregate this data like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>let grouped = {};
  SALES.forEach(({lead, repName, revenue}) =&gt; {
    grouped[[lead, repName]] = grouped[[lead, repName]] || { lead, repName, revenue: 0 };
    grouped[[lead, repName]].revenue = +grouped[[lead, repName]].revenue + (+revenue);
  });
  grouped = Object.values(grouped);
  
  console.warn('Look at this:\n', grouped);
  </code></pre>
  
  <p>However, I would like this to be more dynamic so that I don't have to write an if-else statement for all the possible combinations of groupings and aggregations. The following code shows something that I would like to get working, but currently does not. </p>
  
  <pre class="lang-js prettyprint-override"><code>function groupByTotal(arr, groupByCols, aggregateCols) {
    let grouped = {};
    arr.forEach(({ groupByCols, aggregateCols }) =&gt; {
      grouped[groupByCols] = grouped[groupByCols] || { groupByCols, aggregateCols: 0 };
      grouped[groupByCols].aggregateCols = +grouped[groupByCols].aggregateCols + (+aggregateCols);
    });
    grouped = Object.values(grouped);
    return grouped;
  }
  
  groupByTotal(SALES,['lead','repName'],'revenue')
  </code></pre>
  
  <p>Expected output might look like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>[
    { lead: "Mgr 1", repName: "Rep 1", revenue: 59.98 },
    { lead: "Mgr 1", repName: "Rep 13", revenue: 9.99 },
    { lead: "Mgr 2", repName: "Rep 3", revenue: 99.99 },
    { lead: "Mgr 2", repName: "Rep 5", revenue: 9.99 },
    { lead: "Mgr 3", repName: "Rep 6", revenue: 199.99 }
  ]
  </code></pre>
  
  <p>Ideally, I would like to be able to pass in any number of column names to group by or to be aggregated. Any help would be greatly appreciated. </p>