Home > Software design >  how can i sum total of this objects keys?
how can i sum total of this objects keys?

Time:10-03

[
    {A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},
    {D: 10, C: 22.5, A: 85.7, E: 48.6},
    {B: 93.45, D: 37.1, E: 66.34},
    {A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},
    {C: 0, A: 0, B: 11.7, E: 0},
    {E: 89.4, D: 16.5, B: 29.7, A: 84.5}
]

i try some similar to this, but only works in order arrays, i need the sum of the key´s now

const totals = new Array(StoreResumeRows.length).fill(0)
   StoreResumeRows.map((matrixRow: any) => {
     for(let index = 0; index < totals.length; index  ){
       totals[index]  = matrixRow[index]
   }
 })
 console.log(totals)

the output i need it´s like this

[{A: 217.7, B: 166.75, C: 54.9, D: 76.1, E: 301.04}]

CodePudding user response:

You can use Array.reduce to iterate the objects in your array, using a forEach over Object.entries to add each value from those objects to the totals result:

const StoreResumeRows = [
    {A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},
    {D: 10, C: 22.5, A: 85.7, E: 48.6},
    {B: 93.45, D: 37.1, E: 66.34},
    {A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},
    {C: 0, A: 0, B: 11.7, E: 0},
    {E: 89.4, D: 16.5, B: 29.7, A: 84.5}
]

const totals = StoreResumeRows.reduce((acc, obj) => {
  Object.entries(obj).forEach(([k, v]) => acc[k] = (acc[k] || 0)   v)
  return acc
}, {})

console.log(totals)

  

CodePudding user response:

You can achieve it using Object.entries() and Array.prototype.reduce() and Array.prototype.forEach().

Try like below:

const data = [
  {A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},
  {D: 10, C: 22.5, A: 85.7, E: 48.6},
  {B: 93.45, D: 37.1, E: 66.34},
  {A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},
  {C: 0, A: 0, B: 11.7, E: 0},
  {E: 89.4, D: 16.5, B: 29.7, A: 84.5}
]

const totals = data.reduce((prev, curr) => {
  Object.entries(curr).forEach(([key, value]) => {
    prev[key] = prev[key] ? prev[key]   value : value
  })
  return prev
}, {});

console.log(totals);

CodePudding user response:

You can loop through the array, and see if each objects' keys exist, then add them to the result:

const arr = [
    {A: 47.5, B: 23.4, C: 32.4, D: 12.5, E: 18.2},
    {D: 10, C: 22.5, A: 85.7, E: 48.6},
    {B: 93.45, D: 37.1, E: 66.34},
    {A: 0, D: 0,  C: 0,  B: 8.50, E: 78.5},
    {C: 0, A: 0, B: 11.7, E: 0},
    {E: 89.4, D: 16.5, B: 29.7, A: 84.5}
]

const res = {}
arr.forEach(obj => {
  for (const [key, val] of Object.entries(obj)) {
    res[key] = (res[key] || 0)   val
  }
})

console.log(res)

CodePudding user response:

The inner loop is broken. "index" is not your key.

const totals = {};
 StoreResumeRows.map((matrixRow) => {
  for (const [key, value] of Object.entries(matrixRow)) {
    totals[key] = totals[key] ? totals[key]   value : value;
  }
})

  • Related