Hello all
So I got stuck in the option 4 of this skill path where we have to find the how many times the words have been overused in the story. So made the function and did that with the help of for loop. But the problem is that I didn’t get the results which I expected . So please help me out.
const betterWords = storyWords.filter(words => !unnecessaryWords.includes(words));
console.log(betterWords.length);
let [counter1,counter2,counter3] = [0,0,0];
const usedWords = ()=>{
for(let i = 0; i <= betterWords.length; i++){
if(betterWords.includes("really")) {
counter1 += 1;
}else if(betterWords.includes("very")){
counter2 += 1;
}else if(betterWords.includes("basically")){
counter3 += 1;
}
}
console.log(`The word really is used ${counter1} times.`);
console.log(`The word very is used ${counter2} times.`);
console.log(`The word basically is used ${counter3} times.`);
}
usedWords();
Output I’m getting
The word really is used 183 times.
The word very is used 0 times.
The word basically is used 0 times.
you are iterating over the array with the index of every element, you can use it to check if the current element is equal to these words or not, but on your code, you are checking if the words exist in the whole betterWords array, and that’s why the first “if” will always get executed because the array will always include “really” word.
you should check with every element, not the whole array.
you can write:
Arrays and Strings both have a method called includes.
when we write betterWords.includes() we here using includes with the whole array. But when we write betterWords[i].includes() we are using includes with a string because every element in the array is a string.
you can use includes with the array elements with this code:
if (betterWords[i].includes("really")) {
counter1 += 1;
} else if (betterWords[i].includes("very")) {
counter2 += 1;
} else if (betterWords[i].includes("basically")) {
counter3 += 1;
}
here we are checking if every word betterWrods[i] in the array includes these words (really, very, basically) or not.
But there is a problem in this code imagine this word “every” if we check if it includes “very” or not it will return true!! but we don’t want that! we need to check if the word is identical to “very” or not that’s why we used “===”.