algorithm used to calculate 5 star ratings

前端 未结 14 900
挽巷
挽巷 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:24

    In addition, I am just trying to make practical and full code for all.

    My Json Object Array

    var yourRatingData =[{
            review_id:1,
            customer_id:5,
            customer_name:"Faysal",
            rating:5,
            review_content:"I like this product it's cool and best in quality"
        },
        {
            review_id:2,
            customer_id:6,
            customer_name:"Adams",
            rating:4,
            review_content:"It's quality product though price a bit high"
        },
        {
            review_id:3,
            customer_id:8,
            customer_name:"Jane",
            rating:3,
            review_content:"I like but should improve quality"
        },
        {
            review_id:4,
            customer_id:9,
            customer_name:"Julia",
            rating:1,
            review_content:"It's not good"
        }];
    

    Rating Calculation

    let _5star = yourRatingData.filter(r=>r.rating==5).length;
    let _4star = yourRatingData.filter(r=>r.rating==4).length;
    let _3star = yourRatingData.filter(r=>r.rating==3).length;
    let _2star = yourRatingData.filter(r=>r.rating==2).length;
    let _1star = yourRatingData.filter(r=>r.rating==1).length;
    
    //Sum of individual star.
    let sumOfRating = parseInt( _5star + _4star + _3star + _2star + _1star );
    
    //Total number of rating
    let overallRating = parseInt( 5*_5star + 4*_4star + 3*_3star + 2*_2star +1*_1star );
    
    //Average of all rating
    let averageRating = parseFloat(overallRating/sumOfRating);
    
    //Percentage of each star rating
    let _5starPercentage = parseInt((_5star/totalRating)*100);
    let _4starPercentage = parseInt((_4star/totalRating)*100);
    let _3starPercentage = parseInt((_3star/totalRating)*100);
    let _2starPercentage = parseInt((_2star/totalRating)*100);
    let _1starPercentage = parseInt((_1star/totalRating)*100);
    

    I think it's helpful.

提交回复
热议问题