0

i have input like below,

const data = [
    {
        id: 1,
        count: 3,
     },
     {
         id: 2,
         count: 5,
     },
 ];

now i want to gets the ids in a seperate array and sum of count.

so the expected output should be like below,

const ids = [1, 2];
const sum = 8; // which is the sum of count 3 and 5.

i have tried something like

const ids = data.map(({id: any}) => id; //[1,2]
const count = data.map(({count: any}) => count; // [3,5] 

but how to get ids and sum of count in one step rather than this. also instead of type any what should be the correct types. i am new to programmming and typescript. could someone help me with this. thanks.

  • 1
    You can't get two variables out of one call; you'd need to return an object with two properties (e.g., `{ ids: [1,2], sum: 8 }`) and you could destructure that into two variables (e.g., `const { ids, sum } = { ids: [1,2], sum: 8 };`) The remainder of the question are answered by existing questions: https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array and https://stackoverflow.com/questions/40945388/sum-all-properties-of-objects-in-array – Heretic Monkey Oct 25 '22 at 12:31
  • 2
    [This approach](https://tsplay.dev/WzPqRN) is how I'd do this. If that meets your needs I could write up an answer; if not, what am I missing? (Please mention @jcalz to notify me if you reply) – jcalz Oct 25 '22 at 12:50

0 Answers0