title: Javascript - group array of objects by common values with label
body: <p>I am trying to turn an array of objects into another array of objects by grouping by a specific value and adding that value as label and taking it out of the object in the new array.</p>
  <p><strong>Input:</strong> So for instance I have this array of objects:</p>
  <pre class="lang-js prettyprint-override"><code>let tech = [
    { id: 1, grouping: &quot;Front End&quot;, value: &quot;HTML&quot; },
    { id: 2, grouping: &quot;Front End&quot;, value: &quot;React&quot; },
    { id: 3, grouping: &quot;Back End&quot;, value: &quot;Node&quot; },
    { id: 4, grouping: &quot;Back End&quot;, value: &quot;PHP&quot; },
  ];
  </code></pre>
  <p><strong>Expected:</strong> I am looking to try and figure out how I can get to this, where there is a label for each of the unique groupings and options array containing the values of that grouping.</p>
  <pre class="lang-js prettyprint-override"><code>[
    {
      label: &quot;Front End&quot;,
      options: [
        { id: 1, value: &quot;HTML&quot; },
        { id: 2, value: &quot;React&quot; },
      ],
    },
    {
      label: &quot;Back End&quot;,
      options: [
        { id: 3, value: &quot;Node&quot; },
        { id: 4, value: &quot;PHP&quot; },
      ],
    },
  ]
  
  </code></pre>
  <p>The closest I have been able to get to is using reduce to group by the grouping key:</p>
  <pre class="lang-js prettyprint-override"><code>const groupedTech = tech.reduce((acc, value) =&gt; {
    // Group initialization
    if (!acc[value.grouping]) {
      acc[value.grouping] = [];
    }
   
    // Grouping
    acc[value.grouping].push(value);
   
    return acc;
  }, {});
  </code></pre>
  <p>Which gives me this:</p>
  <pre class="lang-js prettyprint-override"><code>{
    &quot;Front End&quot;: [
      { id: 1, grouping: &quot;Front End&quot;, value: &quot;HTML&quot; },
      { id: 2, grouping: &quot;Front End&quot;, value: &quot;React&quot; },
    ],
    &quot;Back End&quot;: [
      { id: 3, grouping: &quot;Back End&quot;, value: &quot;Node&quot; },
      { id: 4, grouping: &quot;Back End&quot;, value: &quot;PHP&quot; },
    ],
  }
  </code></pre>
  <p>But this returns object not an array and doesn't remove the grouping value. I have not been able to figure out how to group properly because in the array of objects I have not found an efficient way to compare against to see if the grouping exists and if so add to that nested array. Would I be better off using something like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow noreferrer">.map()</a>? Appreciate any leads/learnings!</p>