Home > Software design >  Compare data for two objects in React
Compare data for two objects in React

Time:09-03

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

CodePudding user response:

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);

CodePudding user response:

const questions = [ { "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 result = questions.map((question) => {
  const foundPos = answers.find(answer => answer.word === question.word).choose;
  return `Question ${question.id}: word=${question.word} pos=${question.pos}, and the chosen answer was `  
  foundPos   ` (${foundPos === question.pos})`;

});

console.log (result);


Expected output:
0: "Question 1: word=slowly pos=adverb, and the chosen answer was noun (false)"
1: "Question 2: word=ride pos=verb, and the chosen answer was noun (false)"
2: "Question 3: word=bus pos=noun, and the chosen answer was noun (true)"
3: "Question 4: word=commute pos=verb, and the chosen answer was adjective (false)"
  • Related