Home > Software design >  How do I find an array in an array based on index of another array?
How do I find an array in an array based on index of another array?

Time:12-08

If I select "q1" from questions how do I select also the first array from answers?

This is my code right now:

questions = ["q1", "q2", "q3"]
answers = [
    ["r", "f", "f", "f"],
    ["r2", "f2", "f2", "f2"],
    ["r3", "f3", "f3", "f3"]
];

function pickQuestion() {
if (questions.length > 0) {
    question = questions[Math.floor(Math.random() * questions.length)];
    questions.splice(questions.indexOf(question), 1);
    // find array in answers that matches question and remove it

    answers.splice(answers.indexOf(question), 1);
    return ([question, answerArray]);
} else {
    return ("End of questions");
}}

CodePudding user response:

Here your code in working ;)

questions = ["q1", "q2", "q3"]
answers = [
  ["r", "f", "f", "f"],
  ["r2", "f2", "f2", "f2"],
  ["r3", "f3", "f3", "f3"]
];

function pickQuestion() {
  if (questions.length > 0) {
    randomIndex = Math.floor(Math.random() * questions.length)
    question = questions[randomIndex];
    let answer = answers[randomIndex]

    // Remove played question/answer
    questions.splice(randomIndex, 1);
    answers.splice(randomIndex, 1);
    return ([question, answer]);
  } else {
    return ("End of questions");
  }
}

let a = pickQuestion()
console.log(a)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

function pickQuestion() {
  if (questions.length) {
    // set the index to a random number
    let index = Math.floor(Math.random() * questions.length);
    const question = questions[index];
    const answerArray = answers[index];
    questions.splice(index, 1);
    answers.splice(index, 1);
    return ([question, answerArray]);
  } else {
    return ("End of questions");
  }
}
  • Related