Skip to content
Advertisement

How to compare two arrays of strings, find all matches, when there might be a sentence?

This is a fun one – I am building a profanity checker!

For the purposes of this exercise, let’s have an array of forbidden words, like so:

const forbiddenWords = ['apples', 'oranges', 'blue carrots', 'mushy green peas'];

Then I will have an input field for a user to input the something. It could be an infinite combo of words, but I would like to find ALL instances of the forbidden words and return them as an array. I’ve thought of this function, which gets me really close:

JavaScript

Running the above will make the result of array be ['oranges', 'blue', 'carrots']. How could I build out the function to check for 'blue carrots' or 'mushy green peas' all in one? I’d like the above function to return: ['oranges', 'blue carrots']. Thoughts?

Advertisement

Answer

You can use regex for this situation. This will also give you ability to match with case insensitivity

JavaScript

Also, array.sort((x, y) => x - y); is not required as the values you have are string. You can rely on array.sort() or if you really want to do manual sort, try string.localeCompare(string2)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement