title: Merge duplicates in JavaScript Array
body: <p>I have a stupid problem that at first seems to be simple to solve, but turns out to be tricky.</p>
  
  <p>I have an array of objects, each with two properties: id and value:</p>
  
  <pre><code>[ 
    {id: 2, value: 10}, 
    {id: 4, value: 3},
    {id: 2, value: 2},
    {id: 1, value: 15}
  ]
  </code></pre>
  
  <p>I want to write an algorithm that sums up the values of ones with similar id.
  My end result should be a new array with only the merged objects:</p>
  
  <pre><code>[ 
    {id: 2, value: 12}, 
    {id: 4, value: 3},
    {id: 1, value: 15}
  ]
  </code></pre>
  
  <p>I've tried the following, but it doesn't work:</p>
  
  <pre><code>var arr = [];
  arr.push({id: 2, visit:10}); 
  arr.push({id: 4, visit:3}); 
  arr.push({id: 2, visit:2}); 
  arr.push({id: 1, visit:15}); 
  
  // Deep copy
  var copy = jQuery.extend(true, [], arr);
  var masterArr = [];
  
  for (var i = 0; i &lt; arr.length; i++) {
      var objArr = [];
      objArr.push(arr[i]);
          for (var j = copy.length-1; j &gt; -1; j--) {
          if (arr[i].id === copy[j].id) {
              var q = copy.splice(j,1);
          }
      }
          masterArr.push(objArr);
  }
  </code></pre>
  
  <p>My plan was to first gather all similar objects in separate arrays (objArr), sum them up and put them in an end array (masterArr). I use jquerys extend to make a deep copy (not a reference) and reverse iteration and splice to remove objects thats already been found as "duplicates".</p>
  
  <p>This doesn't work! And it doesn't seem to be a very efficient mehtod to solve my problem. 
  How could I do this? Performance isn't top priority but rather "nice to have"!</p>
  
  <p>Thanks!</p>