I have two or more javascript objects. I want to combine them by adding the values โโof common properties, and then sort them in descending order of values.
eg.
var a = {en : 5,fr: 3,in: 9} var b = {en: 8,fr: 21,br: 8} var c = merge(a,b)
c should look like this:
c = { fr: 24, en: 13, in:9, br:8 }
i.e. both merge objects, the values โโof the shared keys are added, and then the keys are sorted.
Here is what I tried:
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; })
but I do not think that is good. So many loops :( It would be nice if someone could provide less dirty and good code.
Jashwant
source share