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

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

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

[false, false, false, false, false]

Maybe there is something I’m not seeing?

>Solution :

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

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