Find a Random Element in a JSON File in Node.js

Share this video with your friends

Social Share Links

Send Tweet

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.