title: How to sum properties of elements in an object-array?
body: <p>I have this array, and I want to sum property (<code>y</code>) of the array elements when <code>x</code> matches certain criteria. For example, if &quot;x&quot;  has the same string value between &quot;/&quot; and &quot;?&quot; as another object then add their &quot;y&quot; property together.</p>
  <pre><code>const data = [
      {
          &quot;x&quot;: &quot;/shop.html&quot;,
          &quot;y&quot;: 3
      },
      {
          &quot;x&quot;: &quot;/&quot;,
          &quot;y&quot;: 2
      },
      {
          &quot;x&quot;: &quot;/?test324&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/account.html&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/account.html?test1&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/shop.html?test543&quot;,
          &quot;y&quot;: 1
      }
  ]
  </code></pre>
  <p>And it should be like this at the end</p>
  <pre><code>    const expectedResult = [
          {
              &quot;x&quot;: &quot;/shop.html&quot;,
              &quot;y&quot;: 4
          },
          {
              &quot;x&quot;: &quot;/&quot;,
              &quot;y&quot;: 3
          },
          {
              &quot;x&quot;: &quot;/account.html&quot;,
              &quot;y&quot;: 2
          },
         
      ]
  </code></pre>
  <p>So as you can see the 2nd array doesn't have the &quot;?xxx&quot; thing, they are all &quot;merged&quot; based on string value between last &quot;/&quot; and &quot;?&quot;</p>
  <p>Tried to do something like this</p>
  <pre><code>let output = res.data.data.reduce(function (accumulator, cur) {
                      let x = cur.x,
                          found = accumulator.find(function (elem) {
                              elem.x = elem.x.split(&quot;?&quot;)[0];
                              return elem.x == x;
                          });
                      if (found) found.y += cur.y;
                      else accumulator.push(cur);
                      return accumulator;
                  }, []);
  </code></pre>
  <p>But duplicated values doesn't add themselves.</p>
  <p>It returns me this</p>
  <pre><code>[
      {
          &quot;x&quot;: &quot;/shop.html&quot;,
          &quot;y&quot;: 3
      },
      {
          &quot;x&quot;: &quot;/&quot;,
          &quot;y&quot;: 2
      },
      {
          &quot;x&quot;: &quot;/&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/account.html&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/account.html&quot;,
          &quot;y&quot;: 1
      },
      {
          &quot;x&quot;: &quot;/shop.html?test543&quot;,
          &quot;y&quot;: 1
      }
  ]
  </code></pre>
  <p>Any idea?</p>