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 Objects Loop Through Objects Store Objects in Arrays

Spencer Renfro
PLUS
Spencer Renfro
Courses Plus Student 11,133 Points

Need help with displaying all the correct answers

I am trying to display what all the correct answers are, but I can not figure out how to increment through the array of objects correctly to display more than the first answer.

Here is my code:

const questions = [ { question: 'How many planets are in the Solar System?', answer: '8' }, { question: 'How many continents are there?', answer: '7' }, { question: 'How many legs does an insect have?', answer: '6' }, { question: 'What year was JavaScript created?', answer: '1995' } ];

const correct = []; const incorrect = []; let correctAnswers = 0;

for ( let i = 0; i < questions.length; i++ ) { let question = questions[i].question; let answer = questions[i].answer; let response = prompt(question);

if ( response === answer ) { correctAnswers++; correct.push(question); } else { incorrect.push(question); } }

function createListItems(arr) { let items = ''; for (let i = 0; i < arr.length; i++) { items += <li>${arr[i]}</li>; } return items; }

let html = ` <h1>You got ${correctAnswers} question(s) correct</h1> <h2>You got these questions right:</h2> <ol>${ createListItems(correct) }</ol>

<h2>You got these questions wrong:</h2> <ol>${ createListItems(incorrect) }</ol>

<h2>The correct answers are:</h2> <ol>${ createListItems(questions[0].answer) }</ol>

`;

document.querySelector('main').innerHTML = html;

1 Answer

Steven Parker
Steven Parker
231,236 Points

This code is explicitly displaying just the first answer (questions[0].answer), and the function is treating the answer string as an array of characters.

To display the entire collection, you might want to create something similar to the createListItems function that would use a loop to build a list of answers when passed the questions array.. The new function could work much like the existing one, but instead of displaying each item itself (${arr[i]}), it could display the "answer" property of each item (${arr[i].answer}). Give that a try and write again if you need more help.