Matching two arrays in Scala

Viewed 41

I have the following two arrays in Scala:

val array1 = Array("Football","Tennis","Tennis","Golf","Cricket","BasketBall","Golf")

val array2 = Array("Golf","Tennis","Formula1","Rugby")

I want to return the distinct words which match across both arrays. So as "Tennis" and "Golf" appear twice, we would count them as one. I believe you would just do array1.distinct to begin with. I was wondering however, how do I put this into a Scala function?

1 Answers

This is the obvious solution:

(array1.toSet intersect array2.toSet).toArray

However Array is not a full Scala type, so better to use Vector or List depending on how you intended to process the data. The Scala collections have a richer set of methods and inter-operate better.

Related