简体   繁体   中英

How do I find an array in an array based on index of another array?

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");
}}

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)

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");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM