I am working with this API - https://opentdb.com/
I have a sort function which works, I get all the data as expected but when I want to display data to the screen, then only questions are displayed like I want while I only get answers from the last array of answers. Here is my codepen (https://codepen.io/argentinaivan/pen/dyVxLyX) and my JS code:
const APIURL = `https://opentdb.com/api.php?amount=10&type=multiple`;
const something = document.querySelector(".questions");
const answers = document.querySelector(".answers");
function sort(array) {
let currentIndex = array.length;
let randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
async function getQuestions() {
const response = await fetch(APIURL);
const data = await response.json();
displayData(data);
}
function displayData(data) {
const questions = data.results;
let allAnswers = [];
for (let i = 0; i < questions.length; i++) {
allAnswers.push([
...questions[i].incorrect_answers,
questions[i].correct_answer,
]);
}
console.log(allAnswers);
for (let answer of allAnswers) {
console.log(answer);
something.innerHTML = `
${questions
.map(
(question) =>
`<p>${question.question}</p>
<p>${sort(answer)}</p>`
)
.join("")}
`;
}
}
getQuestions();
This API with the query parameters I was using returns an array of ten items. Each array item is an object and one of the properties of that object is ‘question’. So, since I also named each item in map ‘question’, I used ‘question.question’. It is all clear if you see console.logs (at least I hope). Each object also has ‘correct_answer’ property and ‘incorrect_answers’ property, I combined all those answers into one array and then used that sort function to sort the answers. And that complete part of code should output questions and answers on the page.
That is a pretty good explanation. Now how many times are you doing that? Remember, this code is inside a for loop. You are always updating something.innerHTML. So how many times is that going to be updated? After the last update what answer is going to be in there?
It is going to be updated ten times because array has ten items. ‘answer’ is going to be answers for the last question in the array. But I am confused with the fact that questions are displayed correctly, while answers are not - I get all the questions displayed, while only answers for last question are displayed - why is that?
I also tried different approach. Since I have two divs in my html, therefore I tried to loop twice, something like this: https://codepen.io/argentinaivan/pen/dyZPLLG
Idea was to get question then answer, followed by second question and second answer etc (just like in the first codepen link). But it failed miserably as you can see, not only I get all the questions first, but I also have answers repeated numerous times…