Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add third key to array of objects summing up values of second key

I know this might be an easy task though I am struggling quite a lot with this one:

I have an Array of objects looking like this:

[{date: '01-01-2022' , count: 1},
 {date: '02-01-2022' , count: 2},
 {date: '05-01-2022' , count: 9}]

My expected outcome would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{date: '01-01-2022' , count: 1 , sum: 1},
 {date: '02-01-2022' , count: 2 , sum: 3},
 {date: '05-01-2022' , count: 9 , sum: 12}]

or alternatively:

[{date: '01-01-2022' , count: 1},
 {date: '02-01-2022' , count: 3},
 {date: '05-01-2022' , count: 12}]

I can sum up the count array using

    let new_array = [];  
    myarray.reduce( (prev, curr,i) =>  new_array[i] = prev + curr , 0 )
    return (new_array);

but I never manage to let it happen in the original array of objects or adding the thing to the original array of objects.

Thank you in advance!

>Solution :

If you want to mutate the original array don’t create a new one (let new_array = [];), simply iterate over the original and add the property you want to each object.

const input = [{ date: '01-01-2022', count: 1 }, { date: '02-01-2022', count: 2 }, { date: '05-01-2022', count: 9 }]

let sum = 0;
for (const o of input) {
  o.sum = (sum += o.count);
}

console.log(input);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading