I have a post Api in which I want to send the answers based on users input in an array like : userAnswer ["correct", "correct", "wrong", "notAttempted", "correct"] and then replace the correct and wrong answers based on their index in the next section in a different array that is like this :
{ "answersArray": [ "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted", "notAttempted" ], }
const [arry, setArry] = useState([]);
const nextQuestion = (examData) => {
if (studentAnswered == examData[currentQuestion].correct) {
setArry((prevState) => [...arry, "correct"]);
} else if (studentAnswered == null) {
setArry((prevState) => [...arry, "notAttempted"]);
} else {
setArry((prevState) => [...arry, "wrong"]);
}
setCurrentQuestion(currentQuestion + 1);
setStudentAnswered(null);
};
The array is a useState Function and NextQuestion is an onClick function it adds the selected answer to the array onClick or keeps the value null if no options are selected. **I was able to do most of the work. Now I just need to update the correct and wrong answers to the AnswersArray Above based on their indexes. Thanks **
Edit : the first array will store the option that the user selects. Lets say you have 20 questions and the user answers 5 questions. userAnswer ["correct", "correct", "wrong", "notAttempted", "correct"]. the correct and wrong answers need to be pushed into the second array above in which all of the indexes have "notAttempted" value stored. So my question is how can I update the values in Array2 with the values in array1 which is userAnswer. The answersArray should look like this :
{ "answersArray": [ "correct", "correct", "wrong", "notAttempted", "correct", "notAttempted", "notAttempted", "notAttempted", "notAttempted" ], }
The values in userAnswer will be pushed into answersArray based on the index number. I hope this make the question more clear now.
Try using Array methods to replace any value in the array using an index.