不确定为什么会出现此问题,但是由于某种原因我得到了错误的输出。我想做的是获取现有的平均收视率并生成新的收视率。我目前正在解决的情况是,已经计算出平均值的用户需要更改其值。
例如:
User A rates at 5 stars
User B rates at 3 stars
User C rates at 5 star
当前平均星数是:13/3或4.333
现在,如果用户B更改了评分,而我不想浏览所有评分,那么我想说:
鉴于我知道有3个等级,而我要更改的等级是用户C到3,那么我想我可以做到:
13-5 = 8
8 + 3 = 11
11/3 = new average 3.667
var originalRatingVal = originalRating.rating ? originalRating.rating.stars : 0
var currentNumberOfRatings = currentItem.count ? currentItem.count.ratings : 0
var currentAverageTotal = currentNumberOfRatings * overall_rating
var oldNumberOfRatings = currentNumberOfRatings - 1
var newAverage = (currentAverageTotal - originalRatingVal) - oldNumberOfRatings
var newRatingVal = currentRating.rating ? currentRating.rating.stars : 0
var newNumRatings = oldNumberOfRatings + 1;
var oldRatingTotal = newAverage * oldNumberOfRatings;
var newAvgRating = (oldRatingTotal + newRatingVal) / newNumRatings;
这似乎不起作用:
如果我将用户B更改为5,期望newAvgRating等于5,则当前等于5.666666666666667。
任何想法都将非常感谢,谢谢!
答案 0 :(得分:0)
const ratings = [5, 3, 5];
const ratingsTotalled = ratings.reduce((a,b)=>a+b);
const originalAverage = ratingsTotalled/ratings.length;
console.log('original:', originalAverage);
//now, I want to remove a '5' rating
//and replace it with '3'
const alteredTotal = ratingsTotalled - 5 + 3;
const alteredAverage = alteredTotal/ratings.length;
console.log('altered:', alteredAverage);
换句话说:
const originalRatings = {
a: 5,
b: 3,
c: 5,
}
const ratings = Object.values(originalRatings);
const ratingsTotalled = ratings.reduce((a,b)=>a+b);
const originalAverage = ratingsTotalled/ratings.length;
console.log('original:', originalAverage);
//now, I want to remove a '5' rating
//and replace it with '3'
const cAlteredRating = 3;
const alteredTotal = ratingsTotalled - originalRatings.c + cAlteredRating;
const alteredAverage = alteredTotal/ratings.length;
console.log('altered:', alteredAverage);