我正在尝试遍历3个地方并选择平均评价和评分最高的地方。
说我有以下内容。
var places = [{
name: "place 1",
reviews: 100,
rating: 5,
},{
name: "place 2",
reviews: 10000,
rating: 5,
},{
name: "place 3",
reviews: 10000000,
rating: 4,
}];
for (i = 0; i < places.length; i++) {
// loop through and calculate the highest average reviews
var rating = places[i].rating;
var reviews = places[i].reviews;
// work out the average score place 3 should be the highest
}
http://jsbin.com/loyequluke/edit?js,console,output
我想做的任何建议都是在3个地方中找到最高的平均评分。
正确的结果将是3,但我不知道如何解决这个问题吗?
答案 0 :(得分:1)
请检查下面的代码并告诉我这是否适合您。由于我不知道你是如何计算最高分的,我认为它是(rating * reviews) / rating
,根据你得到的价值。您可以运行给定的代码段并亲自查看结果。基本上,你有想法计算,这个最适用于几百个小记录。
var places = [{
name: "place 1",
reviews: 100,
rating: 5,
},
{
name: "place 3",
reviews: 30000000,
rating: 23,
},
{
name: "place 2",
reviews: 10000,
rating: 5,
},{
name: "place 3",
reviews: 10000000,
rating: 4,
}];
var highest = [];
for (i = 0; i < places.length; i++) {
// loop through and calculate the highest average reviews
var rating = places[i].rating;
var reviews = places[i].reviews;
highest.push((rating * reviews) / rating);
// work out the average score place 3 should be the highest
}
var highestRating = highest[0];
var pos = 0;
for (i = 0; i < highest.length; i += 1) {
if (highestRating < highest[i]) {
highestRating = highest[i];
pos = i;
}
}
console.log('Highest Rating: ', highestRating);
console.log('Found at position: ', pos);
console.log('Place with highest score : ', places[pos]);
请告诉我们这是否适合您。