Currently we are grabbing the first element in the array that our JSON data gives us back. We want a random element (or question) from our file.
To get a random element from an array we will use Math.Floor and Math.Random in combination with the array length to get a random question returned to us.
Instructor: [0:00] I have manually added some of the questions to my data file, and I would like to be able to select them at random. At the moment, we had our target.parseData just be the zeroth term. We want this now to be Math.random. We want a random number that is going to be as big as the length of the parseData. [0:21] ParseData.length, this will give me a decimal, so I want to use Math.floor to make sure I get an integer value. Now hopefully, every time I run this, I use to get a random question. According to Greek mythology, who is the first woman on Earth? That was Pandora. Again, in a bingo game, which number is represented by the phrase...? 22.
[0:42] The same approach can be used to find a random element of any array. We're looking at the array's lengths. We're multiplying that by Math.random, and then we're taking the floored value of that. Now, it'll give us a random number between zero and the last element.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!