Home > Software engineering >  How to sum each value inside array of object to new variable
How to sum each value inside array of object to new variable

Time:04-16

I have a data like this :

const fund = 
[
 {
  id: 1234,
  totalAmount: 0,
  data: 
   [
    {
     id: 1234,
     amount: '4.000'
    },
    {
     id: 1234,
     amount: '3.000'
    }
   ]
 },
 {
  id: 12345,
  totalAmount: 0
 },
 {
  id: 123456,
  totalAmount: 0
  data: 
   [
    {
     id: 123456,
     amount: '3.000'
    },
    {
     id: 123456,
     amount: '5.000'
    }
   ]
 }
]

I want to sum the amount inside of data each id to a key called totalAmount. But not all the parent id have data key.

here's my desired output :

const fund = 
[
 {
  id: 1234
  data: 
   [
    {
     id: 1234,
     amount: '4.000'
    },
    {
     id: 1234,
     amount: '3.000'
    }
   ],
  totalAmount: 7000
 },
 {
  id: 12345,
  totalAmount: 0        
 },
 {
  id: 123456,
  data: 
   [
    {
     id: 123456,
     amount: '3.000'
    },
    {
     id: 123456,
     amount: '5.000'
    }
   ],
  totalAmount: 8000
 }
]

I was trying with this code :

fund.forEach((elA, i) => {
        if (elA.data) {
          const total = funders[i].data.reduce((acc, curr) => {
            acc  = parseInt(curr.amount.replace(/\./g, ''))
            return acc
          })
          fund[i] = total ? {...elA, totalAmount: total} : elA;
        }
      })

But it's not summing like i want.

Where's my mistake ?

Please ask me if you need more information if it's still not enough to solve that case.

CodePudding user response:

You need to define the initial value for the reduce iterator.

fund.forEach((elA, i) => {
        if (elA.data) {
          const total = funders[i].data.reduce((acc, curr) => {
            acc  = parseInt(curr.amount.replace(/\./g, ''))
            return acc
          }, 0)
          fund[i] = total ? {...elA, totalAmount: total} : elA;
        }
      });

Another alternative for the same code:

fund.forEach(elA => {
  if (elA.data) {
    const total = elA.data.reduce((acc, curr) => {
      return acc   parseInt(curr.amount.replace(/\./g, ''))
    }, 0)
    elA.totalAmount = total;
  }
});
  • Related