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

178
Views
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 answers
Answer question

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 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!