I am developing a quiz application with questions. I can not solve the problem or solve it very crookedly. There are two arrays:
User Responses:
0:{questionId: "1", answerId: "1"} 1:{questionId: "2", answerId: "4"} 2:{questionId: "2", answerId: "6"} 3:{questionId: "3", answerId: "8"} And the correct answers:
0:{questionId: "1", answerId: "3"} 1:{questionId: "2", answerId: "4"} 2:{questionId: "2", answerId: "6"} 3:{questionId: "3", answerId: "7"} I need to compare two arrays and get something like this:
0:{questionId: "1", result: false} \\ пользователь дал не правильный ответ 1:{questionId: "2", result: true} \\ пользователь дал правильный ответ по второму вопросу, в нем два варианта ответа оба совпали. Иначе false если один из ответов не верен 2:{questionId: "3", result: false} \\ пользователь дал не правильный ответ I can’t do this at all. How to solve this problem?
My decision:
@section scripts { <script> $(document).ready(function () { let userAnswers = []; let answers = []; $('#checkResultBtn').click(function () { $('input:checked', '.card-body').each(function () { userAnswers.push({ questionId: $(this).attr('name'), answerId: $(this).val() }); }); console.log(userAnswers); console.log(answers); diff(userAnswers, answers); }); function diff(userAnswers, answers) { userAnswers.forEach(function (userAns) { answers.forEach(function (ans) { if (userAns['questionId'] == ans['questionId']) { if (userAns['answerId'] == ans['answerId']) console.log(true) else console.log(false) } }); }); } @foreach(var answers in Model){ var answersList = answers.Answers.Where(x => x.Answer == 1); foreach(var answer in @answersList) { <text> answers.push({ questionId: '@answer.QuestionId', answerId: '@answer.Id' }); </text> } } }); </script> } PS
It is worth considering that the array on the part of the user may not be the same length as the array of correct answers.
The user can not answer the question at all.