简体   繁体   中英

How to compare an array of submitted quiz answers with an array of correct answers in javascript

I've built a multiple choice quiz. Some of the questions have a single correct answer (using radio input), others have multiple correct answers (checkboxes).

When the user submits the quiz I collect all of the checked radio boxes and checkboxes and push the id of the answer to an array which heads to the server. It looks like this:

userAnswers = [ '1c', '2d', '3a', '3b', '3c', '3d', '4b', '5c', '5d', '6d', '7c', '7d' ]

On the server I have an array of all the correct answers.

correctAnswers = [ '1c', '2d', '3b', '3d', '4b', '5a', '5d', '6d', '7c', '7d' ]

I've tried using underscore's _.difference function to compare the arrays but that doesn't give me a complete comparison.

Can anyone help me devise a way to grade these quizzes? I think the problem is that some of the questions have multiple answers so technically someone could tick all 4 checkboxes or just one, it makes it harder to compare them.

Maybe using arrays isn't the best way to do this, any suggestions are appreciated!

Maybe using arrays isn't the best way to do this

Yes, you really should use an appropriate data structure for this:

answers = [
  ['c'], // 1
  ['d'], // 2
  ['a', 'b', 'c', 'd'], // 3
  ['b'], // 4
  ['c', 'd'], // 5
  ['d'], // 6
  ['c', 'd'] // 7
]

You could also use an object for "named" questions (instead of indexing them), and possibly drop the array wrapper for single-choice questions, but I'd argue for arrays because of their simplicity here.

If you want to use your original format as input (eg because it's easier to type or your server doesn't support nesting URL query parameters), you can easily convert it to the nested arrays.

Comparing the results with the correct answers question-for-question should be trivial then.

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