Home > Software engineering >  Add third key to array of objects summing up values of second key
Add third key to array of objects summing up values of second key

Time:09-23

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!

CodePudding user response:

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

CodePudding user response:

Here's something that would work for your case since you want to do it in original array of objects:

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

myArray.map((entry, index, arr) => {
    entry.sum = index? arr[index-1].sum   entry.count : entry.count;
    delete entry.count; // Provides alternative outcome, remove for expected outcome
    return entry;
});

console.log(myArray);

CodePudding user response:

we can achieve by map also

   

 

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

const fun = (ar)=>{
  var t = 0
  const get = ar.map((e, i)=> {
    t = t e.count
    const Data = {date : e.date,count : e.count,sum : t}
    return Data
})
  return get
}
console.log(fun(input))

  • Related