使用.reduce在多个数组中的一个索引的总和

问题描述 投票:0回答:1

下图显示了我从HealthKit的计步器中拉出的数组。阵列的步数值为33 + 97 + 75。

Image Here

我不知道如何获取每个数组中的第二个索引并将它们加在一起得到205。

我目前正在使用:

let 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个回答
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'))

请运行上面的代码段

如果你想要ts:

function sum(data, value){
    return data.reduce((a, b) => {
        return a + b[value];
    }, 0);
};
© www.soinside.com 2019 - 2024. All rights reserved.