Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate rating score to number

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?

like image 744
Jenny Mok Avatar asked Nov 04 '25 05:11

Jenny Mok


2 Answers

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);
like image 184
Nina Scholz Avatar answered Nov 06 '25 20:11

Nina Scholz


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);
like image 28
Flyer53 Avatar answered Nov 06 '25 19:11

Flyer53



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!