Filter for specific words, not length



I have a question about the filter() iterator.

I have MDN’ed it, Google’d it and looked at the Iterator lesson again, but I can only find examples for filtering words more than a certain length. The Codecademy Pro project says “There is an array of words that are unnecessary. Iterate over your array to filter out these words.” and suggests using .filter() to do it.

Is this correct?

let betterWords = storyWords.filter(word => word !== 'extremely', 'literally', 'actually');

It will filter out words that are not equal to those three words?. Well, I tried this and it does work but only for ‘extremely’ !

It also doesn’t work if I use an array of words that I wanted filtered:

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let betterWords = storyWords.filter(word => word !== unnecessaryWords);



let betterWords = storyWords.filter(word => word !== 'extremely', 'literally', 'actually');

if you want to do multiple comparisons, you need to use or or and like you learned

this also doesn’t work:

let betterWords = storyWords.filter(word => word !== unnecessaryWords);

given a string (word) will never equal an array (unnecessaryWords)


your 'literally' and 'actually' strings are going to end up as the second and third arguments to the filter function

added a set of parentheses to show how it gets read:
storyWords.filter((word => word !== 'extremely'), 'literally', 'actually');

                 ^                            ^

If you move my closing parentheses to the end:

storyWords.filter((word => word !== 'extremely', 'literally', 'actually'));


Then you won’t have a function at all, that expression evaluates to 'actually' (a string)

Move the first one so that the function body is inside parentheses:

storyWords.filter(word => (word !== 'extremely', 'literally', 'actually'));


And you’ll now have a useless function that always returns the same result: 'actually' (the last expression in the function body)

let f = () => (1, 2, 3)
console.log(f())  // 3

like @stetim94 points out, you’ll need to write your predicate (a function returning true/false) in a way that it’s comparing to each word that you want to compare to. Operators like !== take the value on the left and the value on the right, there’s nothing that would make it aware of what is going on in a different expression (on the other side of your comma)


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