algorithm used to calculate 5 star ratings

前端 未结 14 898
挽巷
挽巷 2021-01-29 17:49

I need to calculate 5-star ratings like the one on Amazon website. I have done enough search to find what is the best algorithm, but I am not able to get a proper answer. For ex

14条回答
  •  再見小時候
    2021-01-29 18:28

    in Javascript

    function calcAverageRating(ratings) {
    
      let totalWeight = 0;
      let totalReviews = 0;
    
      ratings.forEach((rating) => {
    
        const weightMultipliedByNumber = rating.weight * rating.count;
        totalWeight += weightMultipliedByNumber;
        totalReviews += rating.count;
      });
    
      const averageRating = totalWeight / totalReviews;
    
      return averageRating.toFixed(2);
    }
    
    
    const ratings = [
      {
        weight: 5,
        count: 252
      },
      {
        weight: 4,
        count: 124
      },
      {
        weight: 3,
        count: 40
      },
      {
        weight: 2,
        count: 29
      },
      {
        weight: 1,
        count: 33
      }
    ];
    
    console.log(calcAverageRating(ratings));
    

提交回复
热议问题