Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda