Searching by closest and position I wasn't able to find an answer—but found Nearest
by guessing. Nearest
, however, returns the closest number itself, not the position.
After some more looking around, I learned about MapIndexed
and Rules
, and came up with this:
NearestPosition[haystack_, needle_] := Nearest[haystack, needle] /. MapIndexed[Rule, haystack];
Is there a more efficient way, in general?
(And what if it's guaranteed the list comes sorted—can that be leveraged?)
The reason I'm concerned about efficiency is that I intend to use NearestPosition
in a DynamicModule
where it may be triggered by every mouseover
event. (I'm still trying to solve this problem.)
Nearest
would return by default: a list of all "tied" for the closest. (I don't need any ofNearest
's other features, like closest-within-a-radius, closest-n, etc.) $\endgroup$