dCode
dCode

Reputation: 45

Sum of one index in multiple arrays using .reduce

The picture below shows the arrays I am pulling from HealthKit's step counter. The arrays have step count values of 33 + 97 + 75.

Image Here

I'm not sure how to grab the second index in each array and add them together to get 205.

I am currently using:

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

This logs arrays correctly :

console.log(data as any);

This link below is the closest thing I could find, but I am not sure how to apply it to only one index. How to sum elements at the same index in array of arrays into a single array?

Thanks in advance for any help!

I am using Ionic Framework (HTML/CSS files) and Angular (TS files).

Upvotes: 0

Views: 419

Answers (1)

Sravan
Sravan

Reputation: 18647

Here is a function you can write,

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'))

Please run the above snippet

If you want ts:

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

Upvotes: 1

Related Questions