title: JavaScript - Reduce Array of Objects by Key
body: <p>Working with an array of objects like:</p>
  
  <pre><code>const arr = [
    {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
    {name: "survey with select", value: "survey with select answer", count: 2},
    {name: "werasd", value: "Donald", count: 1},
    {name: "werasd", value: "Jim", count: 1}
  ];
  </code></pre>
  
  <p>I am trying to reduce the array on matching values for the <code>name</code> key and achieve an desired output like:</p>
  
  <pre><code>desiredOutput = [
    {name: "qewregf dqewafs", data: [{value: "qewregf dqewafs answer", count: 2}]},
    {name: "survey with select", data: [{value: "survey with select answer", count: 2}]},
    {name: "werasd", data: [{value: "Donald", count: 1}, {value: "Jim", count: 1}]}
  ]
  </code></pre>
  
  <p>This attempt reduces the array, but I am missing how to merge the nested values without overwriting.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [{"name":"qewregf dqewafs","value":"qewregf dqewafs answer","count":2},{"name":"survey with select","value":"survey with select answer","count":2},{"name":"werasd","value":"Donald","count":1},{"name":"werasd","value":"Jim","count":1}];
  
  const result = arr.reduce((acc, d) =&gt; {
    const found = acc.find(a =&gt; a.name === d.name);
    const value = { name: d.name, val: d.value };
    if (found) {
      acc.push(...value);
    }
    else {
      acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
    }
    return acc;
  }, []);
  
  console.log(result);</code></pre>
  </div>
  </div>
  </p>
  
  <p>What am I missing?</p>