Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!