I have two objects one come from API and contain data for each question and another one I created when the user check the answer
API data
"wordList": [
{
"id": 1,
"word": "slowly",
"pos": "adverb"
},
{
"id": 2,
"word": "ride",
"pos": "verb"
},
{
"id": 3,
"word": "bus",
"pos": "noun"
},
{
"id": 4,
"word": "commute",
"pos": "verb"
},
...
]
data create after the user check the answer:
[
{
"word": "slowly",
"choose": "noun"
},
{
"word": "ride",
"choose": "noun"
},
{
"word": "bus",
"choose": "noun"
},
{
"word": "commute",
"choose": "adjective"
}
]
How can I check IF the answer is correct or not to show user the result
>Solution :
This will calculate the score for correct answers using Array.prototype.map():
const wordList = [ { "id": 1, "word": "slowly", "pos": "adverb" }, { "id": 2, "word": "ride", "pos": "verb" }, { "id": 3, "word": "bus", "pos": "noun" }, { "id": 4, "word": "commute", "pos": "verb" }, ]
const answers = [ { "word": "slowly", "choose": "noun" }, { "word": "ride", "choose": "noun" }, { "word": "bus", "choose": "noun" }, { "word": "commute", "choose": "adjective" } ]
const score = answers.reduce((prev, {word, choose}) => {
return wordList.find(item => word === item.word).pos === choose ? prev + 1: prev
}, 0)
console.log(score);