-2

I have the below array with me

scala> Array((65.0,53.0,54.0),(20.0,30.0,24.0),(11.0,19.0,43.0))
res3: Array[(Double, Double, Double)] = Array((65.0,53.0,54.0), (20.0,30.0,24.0), (11.0,19.0,43.0))

How to filter out the items from this array based on the third element ? ie , I am trying to get the item which has the least third element. ie, here the third elements are 54.0, 24.0 and 43.0 and

Expected output -

scala> Array((20.0,30.0,24.0))
res4: Array[(Double, Double, Double)] = Array((20.0,30.0,24.0))
abc_spark
  • 383
  • 3
  • 19
  • What have you tried? Did you check the [**scaladoc**](https://www.scala-lang.org/api/current/)? Do you have any restriction like this has to be done using `while` or without mutable variables or something? What happens if the input is empty? What happens if two values have the same minimum? Finally, do you have to use **Arrays**, or can you switch to using a real collection? – Luis Miguel Mejía Suárez Jun 15 '20 at 14:40
  • You can just call the `min` method with `Ordering.by[(Double, Double, Double), Double](_._3)` – user Jun 15 '20 at 14:43
  • I have tried using .sortBy(_(2)) but, it didnt work since I am getting - error: diverging implicit expansion for type scala.math.Ordering[B] – abc_spark Jun 15 '20 at 14:45

1 Answers1

2

how about,

val a = Array((65.0, 53.0, 54.0), (20.0, 30.0, 24.0), (11.0, 19.0, 43.0))
val l  = a.minBy(_._3)
println(s">>Least third: ${l}")
ameet chaubal
  • 1,440
  • 16
  • 37