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

192
Views
¿Cómo agrupar por propiedad riskTypeNo y calcular la suma y el promedio por valor seleccionado en javascript?

Logré el resultado ejecutando funciones de reducción separadas para suma y conteo y luego creando finalobj usando Object.entries. ¿Se puede lograr esto con menos y mejor código?

{ A1: { Promedio: 4, Recuento: 1, Suma: 4 }, A13: { Promedio: 3, Recuento: 1, Suma: 3 }, A4: { Promedio: 1, Recuento: 1, Suma: 1 }, C6 : { Promedio: 1, Recuento: 1, Suma: 1 }, M1: { Promedio: 1,75, Recuento: 4, Suma: 7 } }

Mi código:

 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 es una gran biblioteca para este tipo de operaciones.

 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!