Mini linter final word count difference

const betterWords = storyWords.filter(function(x){
return !unnecessaryWords.includes(x)}) // THE FINAL WORD COUNT IS 182.

const betterWords = storyWords.filter(function(x){
if (x != unnecessaryWords[0] && x != unnecessaryWords[1] && x != unnecessaryWords[2])
return x}) // THE FINAL WORD COUNT IS 179.

Could anybody tell me why the word count is different when both of these filter functions should do exactly the same job? Many thanks

they don’t do the same thing:

This is either true or false – a bolean. That is what the filter method expects as a return value from the callback function.

This returns the value stored in the filtered array. That is not what the filter function expects. I don’t know why the filter has 3 items less, but the first example is the better solution and probably stores the correct result.

1 Like

Thank you for the response, I put both of the different paragraphs into a WordCounter online and they both have returned 178 words. I do not understand

Do you pass an array to the function as an argument or a string?

I believe as a string

Then that will be the problem. includes() can also search strings for a match, but that will be different than searching an array.

const arr = ['climb', 'hill'];
const str = 'climb hill';

console.log(arr.includes('hi')); // false
console.log(str.includes('hi')); // true

So if you pass a string and look for includes, it will find matches that are just a part of a word as well.

1 Like

Ahhhh thank you so much!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.