Le Kim Trang
Le Kim Trang

Reputation: 459

scala array filtering based on information of another array

I have 2 types of array like this: array one,

Array(productId, categoryId)

   (2, 423) 
   (6, 859)
   (3, 423)
   (5, 859)

and another array Array((productId1, productId2), count)

   ((2, 6), 1), ((2, 3), 1), ((6, 5), 1), ((6, 3), 1)

I would like to filter the second array based on the first array, firstly I want to check array 2 to see if productId1 and productId2 having the same category, if yes, will keep, otherwise will filter out this element. So the list above will be filtered to remain:

   ( ((2, 3), 1), ((6, 5), 1) )

Can anybody help me with this? Thank you very much.

Upvotes: 0

Views: 844

Answers (1)

Shadowlands
Shadowlands

Reputation: 15074

If you don't mind working with the first array as a map, ie:

scala> val categ_info = cats = Array((2, 423), (6, 859), (3, 423), (5, 859)).toMap
categ_info: Map[Int, Int] = Map(2 -> 423, 6 -> 859, 3 -> 423, 5 -> 859)

then we have (setting up example data as simple Ints for convenience):

val data = Array(((2, 6), 1), ((2, 3), 1), ((6, 5), 1), ((6, 3), 1))

data.filter { case ((prod1_id, prod2_id), _) => 
    categ_info(prod1_id) == categ_info(prod2_id) 
}

producing:

res2: Array[((Int, Int), Int)] = Array(((2, 3), 1), ((6, 5), 1))

as requested.

Upvotes: 2

Related Questions