YO Y
YO Y

Reputation: 131

How to get sum values of each of properties

I'd like to get sum values of each of properties

const dataArr = [
    { prop1 : 1,
      prop2 : 10,
      prop3 : 100  
    },
    { prop1 : 2,
      prop2 : 20,
      prop3 : 200  
    },
    { prop1 : 3,
      prop2 : 30,
      prop3 : 300  
    },
]

const result = dataArr.reduce( ( acc, curr ) => {
    return {
        prop1 : acc + curr.prop1,   
        prop2 : acc + curr.prop2,   
        prop3 : acc + curr.prop3   
    }
},0)

console.log(result) 
// expected { prop1 : 6, prop2 : 60, prop3 : 600 }
// but got { prop1 : 3, prop2 : 30, prop3 : 300 }

So, I've tried reduce like this, but it didn't work. How can I fix it?

Upvotes: 2

Views: 97

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

If you have an unknown number of properties, you can use a nested reduce:

const dataArr = [{
    prop1: 1,
    prop2: 10,
    prop3: 100
  },
  {
    prop1: 2,
    prop2: 20,
    prop3: 200
  },
  {
    prop1: 3,
    prop2: 30,
    prop3: 300
  },
]

const result = dataArr.reduce((acc, curr) => {
  return Object.entries(curr).reduce((iAcc, [k, v]) => {
    iAcc[k] = (iAcc[k] ?? 0) + v;
    return iAcc;
  }, acc)
})
console.log(result)

This also works if some elements have missing properties

Upvotes: 3

Chong Lip Phang
Chong Lip Phang

Reputation: 9279

const dataArr = [
    { prop1 : 1,
      prop2 : 10,
      prop3 : 100  
    },
    { prop1 : 2,
      prop2 : 20,
      prop3 : 200  
    },
    { prop1 : 3,
      prop2 : 30,
      prop3 : 300  
    },
];

let sum = dataArr.reduce((a,b)=>({
   prop1: a.prop1+b.prop1,
   prop2: a.prop2+b.prop2,
   prop3: a.prop3+b.prop3,}));
   
console.log(sum);

Upvotes: 4

Related Questions