Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i sum total of this objects keys?

[
    {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}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading