Reputation: 83
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?
Upvotes: 2
Views: 65
Reputation: 495
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);
Upvotes: 2
Reputation: 2319
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);
Upvotes: 3
Reputation: 1069
You need to split wordsIncorrect
as well. if (wordsIncorrect.split(",").includes(word))
Output:
cat
[ false, false, true, false, false ]
Upvotes: 1