Home > OS >  If else not working as intended, is there something wrong with my logic?
If else not working as intended, is there something wrong with my logic?

Time:12-01

I'm trying to loop through an array and if there are any matching elements, it should push true to a new array else return false.

const wordPerformance = []
const wordsReviewed   = "candy, cattle, cat, call, cheat";
const wordsIncorrect  = "candy, cattle, call, cheat";

wordsReviewed.split(/,\s?/).forEach((word) => {
  if (wordsIncorrect.includes(word)) {
    wordPerformance.push(false);
  } else {
    console.log(word) //unreachable, though 'cat' should be logged
    wordPerformance.push(true);
  }
});

console.log(wordPerformance);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

By this logic, wordPerformance should return

[false, false, true, false, false]

however, it is returning

[false, false, false, false, false]

Maybe there is something I'm not seeing?

CodePudding user response:

You have to first split the wordsIncorrect string the same way you did it with the wordsReviewed so it does compare whith the item and not include strings which have something at the end like matching "cat" with "cattle"

This is the fixed example

const wordPerformance = []
const wordsReviewed = "candy, cattle, cat, call, cheat";
const wordsIncorrect = "candy, cattle, call, cheat";
const wordsIncorrectSplitted = wordsIncorrect.split(/,\s?/);

wordsReviewed.split(/,\s?/).forEach((word) => {
  if (wordsIncorrectSplitted.includes(word)) {
    wordPerformance.push(false);
    } else {
    console.log(word) //unreachable, though 'cat' should be logged
    wordPerformance.push(true);
  }
});

console.log(wordPerformance);

enter image description here

CodePudding user response:

You need to split wordsIncorrect as well. if (wordsIncorrect.split(",").includes(word))

Output:

cat
[ false, false, true, false, false ]

CodePudding user response:

You are forgetting to split your incorrectWords string into an array as well. Right now, you are checking if the string includes the word instead of as an array. As a result, String.includes carries out pattern matching across the whole string rather than individual elements. Since every incorrect word includes the pattern cat in them, it will think cat is included and return false:

const wordPerformance = []
const wordsReviewed   = "candy, cattle, cat, call, cheat";
const wordsIncorrect  = "candy, cattle, call, cheat";

wordsReviewed.split(/,\s?/).forEach((word) => {
  if (wordsIncorrect.split(/,\s?/).includes(word)) { //split incorrectWords
    wordPerformance.push(false);
   } else {
     console.log(word) //unreachable, though 'cat' should be logged
     wordPerformance.push(true);
   }
 });

console.log(wordPerformance);
  • Related