I have an array that consist of feedback objects. Each object is a user feedback left for a product:
Array [ {…}, {…} ]
0: Object { id: "1223", quality: 3, material: 4, … }
1: Object { id: "7342", quality: 3, material: 5, … }
...
Users can leave feedback for each category quality
, material
, ... out of 5.
I want to use the weighted average so on my site, I can show for example:
quality: 3
material: 4
This is weighted average calculated by this formula:
quality: (5*0 + 4*0 + 3*2 + 2*0 + 1*0) / (2) = 3
material: (5*1 + 4*0 + 3*1 + 2*0 + 1*0) / (2) = 4
I want to add this my js project, so I loop through all feedback:
const total = []
const feedback = [{
id: "1223",
quality: 3,
material: 4,
},
{
id: "7342",
quality: 3,
material: 5,
}
];
feedback.forEach(function(arrayItem) {
const score = arrayItem.quality
total.push(score)
})
console.log(total.reduce((partialSum, a) => partialSum + a, 0))
I am confused about how to do the calculation for each star, for example to get number of 1s, 2s, 3s, 4s, and 5 starts. How can I modify my code to return the rating result?