Array subtraction array in scala

I am learning Scala ropes and I wonder if there is an easy way to do array subtraction.

Let's say I have two arrays where the elements are of the form (K, V):

A: Array((1,2), (2,3), (4,1))
B: Array((1,1), (2,3))

I would like to get

A - B: Array((1,1), (4,1))

The corresponding keys must be subtracted.

Any help is appreciated. Thanks in advance!

Edit: It seems the word β€œsubtract” is confusing. What I want to do is subtract the values ​​of matching keys in (K, V) pairs in arrays.

+3
source share
3 answers

If you mean that you want to subtract B from A for each suitable key, and if the difference is 0, ignore it, do the following:

val a = Array((1,2), (2,3), (4,1))
val b = Array((1,1), (2,3))

val bMap = b.toMap
a.map{ case (k,v) => (k, v - bMap.getOrElse(k,0)) }.filter(_._2 != 0)
// Array((1,1), (4,1))

b . a b ( 0, ). , , 0.

+5

, , , . A.toSet -- B.toSet.

+3

You can do this using the expression "for expression":

val a = Array((1,2), (2,3), (4,1))
val b = Array((1,1), (2,3))

val bMap = b.toMap
for {
  (k, v) <- a                      // get an element from a
  nv =  v - bMap.getOrElse(k,0)    // calculate the new value
  if (nv > 0)                      // filter the 0 values
} yield (k, nv)                    // yield the updated pair
0
source

All Articles