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

180
Visualizações
How do I calculate average of score based on their ids from api responses

Here are the responses from my API:

const attractions = [
  {"id": 1,"name": "drive on avenue"},
  {"id": 2, "name": "diving"},
  {"id": 3,"name": "visiting mangroove"},
];

const reviews = [
  {"id": 1,"score": 1.5},
  {"id": 2, "score": 2} ,
  {"id": 3,"score": 5.5},
  {"id": 3,"score": 4},
  {"id": 2,"score": 3},
  {"id": 1,"score": 3.5},
  {"id": 3,"score": 5},
  {"id": 2,"score": 4}
]

Expected output:

[{"name": "drive on avenue", "score": 2.5},
{"name": "diving", "score": 3},
{"name": "visiting mangroove", "score": 4.83}
]

I tried using reduce, but that would sum up all scores in one. How can I calculate the average score for each ID?

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

0

Loop through the attractions array and for each one, get the average from the reviews array. Something like this:

const attractions = [
    {"id": 1,"name": "drive on avenue"},
    {"id": 2, "name": "diving"},
    {"id": 3,"name": "visiting mangroove"},
  ];
  
  const reviews = [
    {"id": 1,"score": 1.5},
    {"id": 2, "score": 2} ,
    {"id": 3,"score": 5.5},
    {"id": 3,"score": 4},
    {"id": 2,"score": 3},
    {"id": 1,"score": 3.5},
    {"id": 3,"score": 5},
    {"id": 2,"score": 4}
  ]

var returned = []
attractions.forEach((attraction) => {
    let arr = reviews.filter(x => x.id == attraction.id).map(x => x.score);
    let score = arr.reduce((a, b) => a + b, 0)/arr.length;
    returned.push({ name: attraction.name, score: score});
})

console.log(returned);

map and filter are high-order functions described here:

Map

Filter

In short, map is used here to pull values from an object {id: 1, score: 3} => 3. And filter is used here to filter review and get just the id's we want.

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