Raphael Sanseverino
Raphael Sanseverino

Reputation: 13

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 am trying 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 is like following

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

Upvotes: 1

Views: 123

Answers (4)

symlink
symlink

Reputation: 12208

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)

Upvotes: 1

Amila Senadheera
Amila Senadheera

Reputation: 13265

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

Upvotes: 1

Antonio
Antonio

Reputation: 381

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

Upvotes: 0

Nick
Nick

Reputation: 147286

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)

  

Upvotes: 2

Related Questions