Skip to content
Advertisement

Compare value of two arrays

Five random numbers(from numbers array) will be shown one by one and we need to recall last four number by clicking the number. The answers are push to answer array after clicking. Now i need to compare answers array and number array to calculate the score. My problem is in scoring logic which is not working as expected. When the first guess(or any guess) is correct, then all the remaining guess are also counted as correct even its not.

link: https://codesandbox.io/s/pensive-pascal-rh6e13?file=/src/App.js

Below is the score calculation logic

useEffect(() => {
    if (answers.length) {
      if (numbers[4].num === answers[3]) {
        console.log(
          "match is--------------------------------1",
          numbers[4].num,
          answers[3]
        );
        setScore(score=> score + 1);
      } else if (numbers[3].num === answers[2]) {
        console.log(
          "match is--------------------------------2",
          numbers[3].num,
          answers[2]
        );
        setScore(score=> score + 1);
      } else if (numbers[2].num === answers[1]) {
        console.log(
          "match is--------------------------------3",
          numbers[2].num,
          answers[1]
        );
        setScore(score=> score + 1);
      } else if (numbers[1].num === answers[0]) {
        console.log(
          "match is--------------------------------4",
          numbers[1].num,
          answers[0]
        );
        setScore(score=> score + 1);
      } else {
        console.log("no match---------------------");
      }
    }
  }, [answers, numbers]);

Advertisement

Answer

You might want to simplify your calculation logic with a loop like that:

useEffect(() => {
    console.log("Checking result", answers, numbers);
    if (answers.length < numbers.length - 1) {
        return;
    }
    let i = 0;
    while (i < numbers.length - 1) {
        if (numbers[i + 1].num === answers[i]) {
            console.log("match is--------------------------------1");
            setScore((score) => score + 1);
        }
        i++;
    }
}, [answers, numbers]);

Here you have a fork of your demo with the changes I describe below:

https://codesandbox.io/s/elegant-sara-zftstd?file=/src/App.js

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement