2015-03-03 70 views
1

我想總結一下數組'data'中的調用次數。我找到了'reduce'函數,但不知道如何選擇數組的調用部分。這是我嘗試在做它:使用javascript中的變量減少數組中的變量求和

data = { 
     links: [ 
        {source: 0,target: 1, calls: 20, texts:0}, 
        {source: 0,target: 2, calls: 5, texts:0}, 
        {source: 0,target: 3, calls: 8, texts:0}, 
        {source: 0,target: 4, calls: 3, texts:0}, 
        {source: 0,target: 5, calls: 2, texts:0}, 
        {source: 0,target: 6, calls: 3, texts:0}, 
        {source: 0,target: 7, calls: 5, texts:0}, 
        {source: 0,target: 8, calls: 2, texts:0} 
       ] 
     } 

var total_calls = data.links.calls.reduce(function(a, b) { 
    return a + b; 
}); 

回答

1

如何使這一多一點點的可重複使用的?

data = { 
 
     links: [ 
 
        {source: 0,target: 1, calls: 20, texts:0}, 
 
        {source: 0,target: 2, calls: 5, texts:0}, 
 
        {source: 0,target: 3, calls: 8, texts:0}, 
 
        {source: 0,target: 4, calls: 3, texts:0}, 
 
        {source: 0,target: 5, calls: 2, texts:0}, 
 
        {source: 0,target: 6, calls: 3, texts:0}, 
 
        {source: 0,target: 7, calls: 5, texts:0}, 
 
        {source: 0,target: 8, calls: 2, texts:0} 
 
       ] 
 
     } 
 

 
pluck = function(ary, prop) { 
 
    return ary.map(function(x) { return x[prop] }); 
 
} 
 

 
sum = function(ary) { 
 
    return ary.reduce(function(a, b) { return a + b }, 0); 
 
} 
 

 
result = sum(pluck(data.links, 'calls')) 
 
document.write(result)

+0

兩種解決方案都相當不錯,但我的目的,它實際上是完美這是可重複使用的。 – pir 2015-03-03 11:38:49

3

您需要遍歷數組data.links,這樣

var total_calls = data.links.reduce(function(result, currentObject) { 
    return result + currentObject.calls; 
}, 0); 
console.log(total_calls); 
// 48