Search code examples
javascriptarrayssumjavascript-objects

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:

[{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);