【问题标题】:Sum of one index in multiple arrays using .reduce使用 .reduce 对多个数组中的一个索引求和
【发布时间】:2018-01-04 06:21:47
【问题描述】:

下图显示了我从 HealthKit 的计步器中提取的数组。数组的步数值为 33 + 97 + 75。

Image Here

我不确定如何获取每个数组中的第二个索引并将它们相加得到 205。

我目前正在使用:

让 stepSum = (data as any).reduce((a, b) => a + b.quantity, 0);

这会正确记录数组:

console.log(任何数据);

链接是我能找到的最接近的链接,但我不确定如何仅将其应用于一个索引。 How to sum elements at the same index in array of arrays into a single array?

提前感谢您的帮助!

我正在使用 Ionic Framework(HTML/CSS 文件)和 Angular(TS 文件)。

【问题讨论】:

  • 分享您的数据和预期输出。

标签: arrays angularjs indexing sum


【解决方案1】:

这是一个你可以写的函数,

function sum(data, value){
    return data.reduce( function(a, b){
        return a + b[value];
    }, 0);
};

var data = [{ startDate: '', endDate: '', value: 33},
{ startDate: '', endDate: '', value: 97},
{ startDate: '', endDate: '', value: 75}]

alert(sum(data, 'value'))

请运行上面的sn-p

如果你想要 ts:

function sum(data, value){
    return data.reduce((a, b) => {
        return a + b[value];
    }, 0);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2020-07-08
    • 2016-10-12
    • 1970-01-01
    • 2013-05-21
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多