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

200
Views
how to group by riskTypeNo property and calulate sum and averge by selectedValue in javascript?

I have achieved the result by running separate reduce functions for sum and count and then creating finalobj using Object.entries. Can this be achieved with less and better code:

{ A1: { Avg: 4, Count: 1, Sum: 4 }, A13: { Avg: 3, Count: 1, Sum: 3 }, A4: { Avg: 1, Count: 1, Sum: 1 }, C6: { Avg: 1, Count: 1, Sum: 1 }, M1: { Avg: 1.75, Count: 4, Sum: 7 } }

My Code:

const riskTypeNoWithSelectedValue = [
  {
    "riskTypeNo": "A1",
    "selectedValue": 4
  },
  {
    "riskTypeNo": "M1",
    "selectedValue": 4
  },
  {
    "riskTypeNo": "C6",
    "selectedValue": 1
  },
  {
    "riskTypeNo": "M1",
    "selectedValue": 1
  },
  {
    "riskTypeNo": "M1",
    "selectedValue": 1
  },
  {
    "riskTypeNo": "A4",
    "selectedValue": 1
  },
  {
    "riskTypeNo": "M1",
    "selectedValue": 1
  },
  {
    "riskTypeNo": "A13",
    "selectedValue": 3
  }
];

const sumrRiskTypeNo = riskTypeNoWithSelectedValue.reduce((accumulator, {riskTypeNo,  selectedValue}) => (accumulator[riskTypeNo] = (accumulator[riskTypeNo] || 0) + selectedValue, accumulator), {});

        
        const countRiskTypeNo = riskTypeNoWithSelectedValue.reduce((accumulator, {riskTypeNo,  selectedValue}) => (accumulator[riskTypeNo] = (accumulator[riskTypeNo] || 0) + 1, accumulator), {});


const finalObj = {};
Object.entries(sumrRiskTypeNo).forEach(([k, v]) => {
    finalObj[k] = {"Sum": v, "Count": countRiskTypeNo[k], "Avg": v/countRiskTypeNo[k]}; 
});

console.log(finalObj);

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

0

Lodash is a great library for these types of operations.

const data = _.chain(riskTypeNoWithSelectedValue)
  .groupBy(x => x.riskTypeNo)
  .mapValues(list => ({
    "Count": list.length,
    "Sum": _.sum(list),
    "Avg": _.mean(list),
  }))
  .value();

https://codesandbox.io/s/lodash-playground-forked-00n249?file=/src/index.js:515-714

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!