The following code produces a value for -1 for index. Why is that?
val values = Array(1.0, 2.0, 3.0, Double.NaN, 4.0)
val index = values.indexOf(Double.NaN)
println(s"index = $index")
What is the best way to find the index of NaN in this scenario? I have the following solution but don't think that's the most elegant one.
val index2 = values.zipWithIndex.find(_._1.isNaN).get._2
println(s"index2 = $index2")
indexWhere is like indexOf but allows you to provide your own predicate (which is necessary here since Double.NaN != Double.NaN):
scala> values.indexWhere(_.isNaN)
res0: Int = 3
This will be a little more efficient than your solution, and doesn't throw an exception if none of the elements are NaN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With