One way to approach this is by implementing a random word selection function like the following:
function getRandomWord(jsonStringListOfWords) {
var words = JSON.parse(jsonListOfWords);
var MAX_LENGTH = Object.keys(words).length;
var wordLength = Math.floor(Math.random() * MAX_LENGTH) + 1;
var wordIndex = Math.floor(Math.random() * words[wordLength].length) + 1;
return words[wordLength][wordIndex];
}
This method randomly determines the length of the word first, then selects a word from the list that matches that length. However, it may not produce an even distribution among all words with various lengths.
Alternatively, here's an algorithm that ensures an equal chance for each word regardless of its length:
function getRandomWordEvenDistribution(jsonStringListOfWords) {
var words = JSON.parse(jsonListOfWords);
var numWords = 0;
for (var x in words) {
numWords += words[x].length;
}
var wordIndex = Math.floor(Math.random() * numWords);
for (var x in words) {
if (wordIndex >= words[x].length) {
wordIndex -= words[x].length;
} else {
return words[x][wordIndex];
}
}
}
To load the JSON data, you can consider using jQuery's $.getJSON()
method, which facilitates fetching JSON content from your server.