'How can I compare two arrays and run a function depending on the number of matching items (regardless of index)?
I had a previous solution with .forEach that didn't consider the fact that the answers can be selected in the wrong order, so the items at to be at the same exact index. If it was selected in the wrong order it wouldn't match (even though it was the right answer).
Now I'm trying a solution with .every, but it's not changing score when the button "check answers" is clicked. In case you'd like to check the entire code here it is (it's a bit too much to type in - I'm new to stackoverflow so lmk if a better method is suggested to share multiple components): https://replit.com/@arshia93/Quizzical#sections/QuizData.jsx
function scoreQuiz(allCorrectAnswers, selections) {
let totalScore = 0;
if(allCorrectAnswers.length === selections.length) {
return allCorrectAnswers.every((element, index) => {
element === selections[index] ? totalScore++ : totalScore
})
setScore(totalScore)
}
setFinished(!finished)
}
Solution 1:[1]
I looked at your code in the replit you linked. I think the issue is at line 41 where you return the result of calling every method on your allCorrectAnswers array. So, after the every method is done executing you return the value true or false and you exit the scoreQuiz function before you reach the next line where you would have setScore for your quiz. So, you should remove the return statement and let the setScore and setFinished hooks execute.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alonealgorithm |
