Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Arrays Multidimensional Arrays Improve the Quiz – One Solution

My Solution

 // 1. Create a multidimensional array to hold quiz questions and answers

const quiz = [
       ['What is 2 + 2', '4'], 
       ['What animal has a very long neck', 'giraffe'], 
       ['What is the capital of Canada', 'ottawa']
];

// 2. Store the number of questions answered correctly and incorrectly
let correctAnswers = 0;
const correctQuestions = [];
const incorrectQuestions = [];

/* 
  3. Use a loop to cycle through each question
      - Present each question to the user
      - Compare the user's response to answer in the array
      - If the response matches the answer, the number of correctly
        answered questions increments by 1
*/

for (let i = 0; i < quiz.length; i++) {
  let answer = prompt(`${ quiz[i][0] }`);

  if (answer.toLowerCase() === quiz[i][1] ) {
    correctAnswers += 1;
    correctQuestions.push('<li>' + quiz[i][0] + '</li>');
  } else {
    incorrectQuestions.push('<li>' + quiz[i][0] + '</li>');

  }
}


// 4. Display the number of correct answers to the user

document.querySelector('main').innerHTML = `
<h1>Your Score is ${correctAnswers} out of ${quiz.length}</h1>
<h2>You got these questions correct:</h2>
<ol>${correctQuestions.join('')}</ol>
<h2>You got these questions incorrect:</h2><ol>${incorrectQuestions.join('')}</ol>`;

1 Answer

Good job!