使用javascript中的reduce对数组中的变量求和

时间:2015-03-03 11:07:30

标签: javascript arrays

我想总结一下我的数组'数据'中的来电次数。我发现了'减少'功能,但不知道如何选择数组的调用部分。我试图这样做:

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;
});

2 个答案:

答案 0 :(得分:3)

你需要迭代data.links数组,就像这样

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

答案 1 :(得分: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)