title: Merge two javascript objects adding values of common properties
body: <p>I have two or more javascript objects. I want to merge them adding values of common properties and then sort them in descending order of values.</p>
  
  <p>e.g.</p>
  
  <pre><code>var a = {en : 5,fr: 3,in: 9}
  var b = {en: 8,fr: 21,br: 8}
  
  var c = merge(a,b)
  </code></pre>
  
  <p><code>c</code> should then be like this:</p>
  
  <pre><code>c = {
  fr: 24,
  en: 13,
  in:9,
  br:8
  } 
  </code></pre>
  
  <p>i.e. both objects are merge, values of common keys are added and then keys are sorted.</p>
  
  <p>Here's what I've tried:</p>
  
  <pre><code>var a = {en : 5,fr: 3,in: 9}
  var b = {en: 8,fr: 21,br: 8}
  c = {}
  
  // copy common values and all values of a to c
  for(var k in a){
    if(typeof b[k] != 'undefined'){  
      c[k] = a[k] + b[k]  
    }
    else{ c[k] = a[k]}
  }
  
  // copy remaining values of b (which were not common)
  for(var k in b){
   if(typeof c[k]== 'undefined'){
    c[k] = b[k]
   }
  } 
  
  // Create a object array for sorting
  var arr = [];
  
  for(var k in c){
   arr.push({lang:k,count:c[k]})
  }
  
  // Sort object array
  arr.sort(function(a, b) {
     return b.count - a.count;
  })
  </code></pre>
  
  <p>but I dont think its good. So many loops :( It would be nice if someone can provide a less messy and good code.</p>