1

I would like to know is it possible to rate one thing from 1-5 and then calculate its average? For example I have product "milk" with "rate":0. Would it be possible to count how many users have rated it and then do the calculation rate/how many users have given the rating = rating?

To make things clear: I rate milk with 3 and you rate it with 1 then the average is (3+1)/2 = rate: 2

Should I do this calculation user end or it is possible to do it Firebase end?

What logic I should use for this?

The hardest thing is to keep count how many users have rated the product. I think I can do other things.

Should I make new key:value like count and increase the count every time user rates?

Edit: I tried something like this but this leads to nil:

let rate =  self.productsValue[indexPath.row]["rate"] as? Int
            print("rate",rate)
let count = self.productsValue[indexPath.row]["count"] as? Int
            print("count",count)            
let rating = Int(rate!) / Int(count!)
            print(rating)
Tarvo Mäesepp
  • 4,477
  • 3
  • 44
  • 92

1 Answers1

-1

To both get the average rating and how many users that gave it a certain rating, I suggest this kind of JSON tree:

Products
  Milk:
    ...
    nrOfUsersGivenRating0: 15
    nrOfUsersGivenRating1: 54
    nrOfUsersGivenRating2: 12
    nrOfUsersGivenRating3: 32
    nrOfUsersGivenRating4: 21
    nrOfUsersGivenRating5: 65

Then you can on the client-side calculate the total number of users that voted, the average rating and easily get how many users that voted for a certain rating. Hope it helps!

oscarb
  • 36
  • 3