function getRandomWords () {
let words = getServerData("http://localhost:3000/words").then(
data => randomWorldExample(data)
);
let howManyWords = document.querySelector("#words-to-memorize");
let randomElement = words[0].words.sort(() => 0.5 - Math.random())
console.log("random words: ", randomElement.slice(0, howManyWords));
}
This should get ya there. What we are doing is randomly sorting the array then we are slicing the array to the n value.
My working solution finally was the following:
function getRandomWords() {
let words = getServerData('http://localhost:3000/words').then(data => {
const wordsToMemorize = document.querySelector('#words-to-memorize');
document.querySelector("#wordsInput").addEventListener("click", function() {
let temp = wordsToMemorize.value;
selectedtombelemek.innerHTML = "";
for(let i = 0; i < temp; i++) {
let rander = Math.floor(Math.random() * 3000);
selectedtombelemek.innerHTML += data[rander] + "</br>";
}})
});
}
I just started to practice Javascript and I have a json file with a bunch of words. I want to display as many words as the given user input. If user input is 4 then 4 words will be displayed randomly from the server. I can successfully get the data from te server and display all of them in a table but the logic of displaying random words from the server is a little difficult for the firs try and I would like to get a better understanding how to approach it in my case. The getRandomWords()
function is where I was trying to approach something.
words.json
{
"words":
[
"a",
"abandon",
"ability",
"able",
"abortion",
"about",
"above",
"abroad",
"absence",
"absolute",
"absolutely",
"absorb",
"abuse",
"academic"
]
}
snippet from project.js
function getServerData(url) {
let fetchOptions = {
method: "GET",
mode: "cors",
cache: "no-cache"
};
return fetch(url, fetchOptions).then(
response => response.json(),
err => console.error(err)
);
}
document.querySelector("#server-button").addEventListener("click", function() {
getServerData("http://localhost:3000/words").then(
data => fillDataTable(data, "wordTable")
);
});
function getRandomWords() {
let words = getServerData("http://localhost:3000/words").then(
data => randomWordExample(data)
);
var howManyWords = document.querySelector("#words-to-memorize");
const randomElement = words[Math.floor(Math.random() * words.length)];
console.log("random words: ", randomElement);
}
index.html
<div class="row">
<div class="col-2"></div>
<div class="col-8">
<div class="form-group">
<label for="words-to-memorize">How many words you want to see?</label>
<input type="text" class="form-control" id="words-to-memorize">
</div>
<button id="get-words-button" class="button btn btn-block btn-primary">
Get the words
</button>
</div>
<div class="col-2"></div>
</div>
Hey, thanks for the explanation (+1). It still doesn’t seem to be working. I’m not sure if I assigned well
yeah your getting into Promises here, check out this link, it goes over promises and async/await lightly