0

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

1
  • Share your data and expected output. Commented Jan 4, 2018 at 6:24

1 Answer 1

1

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);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.