Skip to content
Advertisement

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

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

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?

Advertisement

Answer

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

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