Object.Reduce not returning the right value

I need to sum all valorReal values which are inside an array demonstrativo inside the object demonstrativoIr, there are 25 objects with valorReal values around 300, and the returning sum value is 416. Not sure what im doing wrong here

this is the reduce

.subscribe((data: any[]) => {
      this.movimento = data.reduce((a,b)=> ({
        ...a,
        dataMovimento: a.dataMovimento,
        valor: a.valor + b.valor,
        valorReal: a.demonstrativoIr.demonstrativo[0].valorReal + b.demonstrativoIr.demonstrativo[0].valorReal 
      }))

This is the original data result

Upvotes: 0

Views: 44

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138257

You just sum up the valorReal of the last two elements (a and b at the last iteration, everything before will be ignored). You could instead take the valorReal inside the accumulator:

  this.movimento = data.reduce((acc, el) => ({
    ...acc,
    valor: acc.valor + el.valor,
    // Take the accumulated value here:
    valorReal: acc.valorReal + el.demonstrativoIr.demonstrativo[0].valorReal 
  // Ensure it is 0 and not undefined at the first iteration:
  }), {valor: 0, valorReal: 0});

Upvotes: 1

Related Questions