I have 5 stars, and each time a user can choose to rate from 1-5. so I have array of score like this
stars = [0,0,2,3,5] // I have this in database
2 user rated 3 stars, 3 users gave 4 stars and 5 user gaved 5 stars, but how do I calculate the score to show in the client side?
You could sum the weighted values and divide by the count of the ratings.
var stars = [0, 0, 2, 3, 5],
count = 0,
sum = stars.reduce(function (sum, item, index) {
count += item;
return sum + item * (index + 1);
}, 0);
console.log(sum / count);
Another solution that works just as well but might be easier to understand.
var stars = [0, 0, 2, 3, 5],
count = 0,
sum = 0;
stars.forEach(function(value, index){
count += value;
sum += value * (index + 1);
});
console.log(sum / count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With