0

I'm creating a website that randomly chooses a place for you to eat. It accesses yelp api and returns 10 results. I want to randomly pick 1 of those results and publish that onto my website. I'm looking for any suggestions about how to do this using javascript. I know you can do it using php but would prefer to use js if i can.

Because the data will be constantly changing as it's based on user input I can't assign each place with a number and then use math.random.

Does anyone have any suggestions on what I could use?

  • 1
    **Congratulations!** you won the _"vague question of the day"_ contest! How the data looks like? care to show us your code? – gdoron May 29 '12 at 12:57
  • 1
    [Stack Overflow is not a Recommendation Engine](http://meta.stackexchange.com/a/128562/177538). Do something first, and come back when you get stuck, or go to CodeReview for peer review of your code. – Joseph May 29 '12 at 13:00
  • 1
    If you have 10 items, put them in an array (if not already) and choose one randomly. See http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array. – Felix Kling May 29 '12 at 13:00
  • @gdoron Actually, my vote would go to [this question](http://stackoverflow.com/questions/10799645/i-would-like-to-create-a-boolean-variable-in-jquery) – Shawn Chin May 29 '12 at 13:03

1 Answers1

0

Since the Yelp! Search API returns an array of matching businesses, you can just use a random integer offset from 0-9 to return one of those:

Math.floor(Math.random() * 10)

However, that'll limit you to the first 10 hits.

A better approach is to do a search with a limit of 1, find out how many hits that results in (via the total property) and then generate a random number from 0 to total and use that as the offset in a second request.

API is defined here: http://www.yelp.com/developers/documentation/v2/search_api

Dancrumb
  • 26,597
  • 10
  • 74
  • 130