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

268
Visualizações
How do you calculate the average of JSON values and iterate this x amount of times with Javascript?

I have a JSON data set which looks like this:

 {
   name: "Evelyn",
   assignment: "SCRUM",
   difficulty: 3,
   fun: 4
 }

Etc.

I am trying to calculate the average of the difficulty and fun values for each assignment. Because I have 10 sets/individuals with 56 assignments, my idea is to first filter on the assignments which should produce 56 sets of assignments with 10 values for each fun and difficulty and then calculate the average for each.

I am struggling with putting this plan into action because I do not know how to make this new JSON data set/array decently. I am thinking about map, reduce etc. but simply struggle putting it into action. Is there a simple way to do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can group the data by assignment, using Array.reduce().

Once we've grouped the data, we can get the average for both difficulty and fun.

let data = [{ name: "Evelyn", assignment: "SCRUM", difficulty: 3, fun: 4 }, { name: "Bill", assignment: "SCRUM", difficulty: 1, fun: 3 }, { name: "Carol", assignment: "SCRUM", difficulty: 2, fun: 5 }, { name: "Evelyn", assignment: "PLANNING", difficulty: 5, fun: 3 }, { name: "Bill", assignment: "PLANNING", difficulty: 6, fun: 1 }, { name: "Carol", assignment: "PLANNING", difficulty: 1, fun: 2 } ]
 
const groupedData = Object.values(data.reduce((acc, { name, assignment, difficulty, fun }) => { 
     acc[assignment] = acc[assignment] || { assignment, difficulty: 0, fun: 0, participants: 0 };
     acc[assignment].difficulty += difficulty;
     acc[assignment].fun += fun;
     acc[assignment].participants++;
     return acc;
}, {}))

const result = groupedData.map(({ assignment, participants, difficulty, fun }) => { 
    return { 
        assignment,
        participants,
        averageDifficulty: difficulty / participants,
        averageFun: fun / participants
    }
});
 
console.log(result)
 
.as-console-wrapper { max-height: 100% !important; }

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