-3

I am trying to loop through 3 places and select the place with the highest average reviews and rating.

Say i have the following.

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

Any suggestions what i want to do is find the highest average rating, out of the 3 places.

The correct result would be place 3, but i dont know how to work this out any help please?

user1503606
  • 3,872
  • 13
  • 44
  • 78

1 Answers1

2

Please check the code below and let me know if this works for you or not. Since I don't know how you are calculating the highest score, I assume it's (rating * reviews) / rating according to which you get the value. You may run the code snippet given and see the result for yourself. Basically, you have the idea to calculate, this best works for small records with few hundred.

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]);

Let us know if this works for you or not.

Samundra
  • 1,869
  • 17
  • 28