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.
e.g.
var a = {en : 5,fr: 3,in: 9}
var b = {en: 8,fr: 21,br: 8}
var c = merge(a,b)
c
should then be like this:
c = {
fr: 24,
en: 13,
in:9,
br:8
}
i.e. both objects are merge, values of common keys are added and then keys are sorted.
Here's what I've 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 dont think its good. So many loops :( It would be nice if someone can provide a less messy and good code.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…