Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird result for Array.indexOf

Tags:

scala

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")
like image 287
Saket Avatar asked Dec 12 '22 00:12

Saket


1 Answers

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.

like image 72
Travis Brown Avatar answered Dec 30 '22 23:12

Travis Brown