Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare data for two objects in React

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
        "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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading