I want to iterate though an array of different ratings, sort by each unique id, sum and calculate the average of each id's ratings. Then save the averages in a new array, where I can call something like averageRating[i], where each entry will be each id's rating.
The original array of objects looks like this, where id could be any number.
data = [{id: 1, rating: 1}, {id: 1, rating: 3}, {id: 1, rating: 1}, {id: 1, rating: 4}, {id: 1, rating}, {id: 2, rating: 3}, {id: 3, rating: 5}, {id: 1, rating: 5}, {id: 1, rating: 5}, {id: 1, rating: 5, {id: 1, rating: 1}, {id: 2, rating: 4}, {id: 1, rating: 3}, {id: 1, rating: 2}]
I was able to do this work it out with only one particular id, doing something like as follows, but having some trouble working out how to do with a dynamic number of ids.
var [average, updateAverage] = useState(0);
let ratings = data.map((item) => item.rating);
// Calculate average of the array
let sum = ratings.reduce((a, b) => a + b, 0);
let avg = sum / ratings.length || 0;
let avgRounded = Math.round(avg); // Round to nearest whole number
updateAverage = avgRounded;