使用javascript中的变量减少数组中的变量求和

问题描述:

我想总结一下数组'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; 
}); 

如何使这一多一点点的可重复使用的?

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

您需要遍历数组data.links,这样

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