Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Words from One List with Words from Another

I'm a relatively new programmer learning scala and functional programming through a udemy class.

I am seeking to filter a list of strings based on another list of strings. I would like to reduce the first list down, so that when I print it out, it only contains the words - "rob", "learns", "scala"

Here's the code I am working with:

val list1:Array[String] = Array("rob","you", "to","learns", "your", "the","scala", "a")

val badWords:Array[String] = Array("you", "to", "your", "the", "a")

val list2 = list1.map(x => badWords.map(badWord => list1.filter(word => word != badWord)))

for (word <- list2) {
  println(word)
}

My logic is that for each word from list1, I then try to compare each badWord element against the current list1 item to determine if it should be filtered or not.

I have run this successfully by hardcoding in what I want to have filtered, such as val list2 = list1.filter(_ != "to"). Obviously, I want give this the capability to scale, so I would like to learn how to pair the filter and map functions (if that is the correct approach).

Thanks in advance, let me know if I should provide further information or context.

like image 617
Rob Z Avatar asked Mar 10 '23 20:03

Rob Z


1 Answers

You can use a very simple snippet for this:

list1.filter(!badWords.contains(_))

This will remove all the words that are also in the badWords List. Im not sure if this will work with arrays however so I suggest using Lists instead.

Example:

val words = List("Hello", "Hello", "World")
val badWords = List("Hello")
val filteredWords = words.filter(!badWords.contains(_))
like image 109
Vogon Jeltz Avatar answered Mar 13 '23 05:03

Vogon Jeltz