Jill Clover
Jill Clover

Reputation: 2328

How to use map within Array[Array]

I want to apply a simple anonymous function to every element in a Array[Array], and output a Array[Array]. This function basically convert all positive numbers into 1, all negatives -1.

I know how to do the same thing for Array, but not Array[Array]. Is there a way to unwrap it?

val data = Array(Array(1,2),Array(-1,-2))
data.map(x => x.map{if (y > 0.0) 1.0 else 0.0})

Upvotes: 0

Views: 64

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31222

first map would give you each Array[T], second map would give you each element in that array.

given,

scala> val data = Array(Array(1,2),Array(-1,-2))
data: Array[Array[Int]] = Array(Array(1, 2), Array(-1, -2))

here's how you can apply function on each elem of second array,

scala> data.map(_.map(elem => if (elem > 0) 1 else -1 ))
res0: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))

You can also use collect,

scala> data.map(_.collect{case elem if elem > 0 => 1 case _ => -1 })
res1: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))

To simplify the same work using a function,

scala> def plusOneMinusOne(x: Int) = if (x > 0) 1 else -1
plusOneMinusOne: (x: Int)Int

scala> data.map(_.map(plusOneMinusOne)) 
res3: Array[Array[Int]] = Array(Array(1, 1), Array(-1, -1))

Upvotes: 4

Related Questions