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?
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:
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.