# Findnearest function?

**URL:** <https://discourse.julialang.org/t/findnearest-function/4143>\
**Category:** General Usage\
**Created:** [June 7, 2017, 6:07pm UTC](https://discourse.julialang.org/t/findnearest-function/4143 "2017-06-07T18:07:42Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![traktofon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/traktofon/32/591_2.png) [@traktofon](https://discourse.julialang.org/u/traktofon)\
**Post date:** [June 8, 2017, 2:08am UTC](https://discourse.julialang.org/t/findnearest-function/4143/5 "2017-06-08T02:08:45Z")

</div>

Like @cormullion, I’ve had need for such a function many times, and here is my personal solution for it. Unlike @Dan’s version, this doesn’t care about ties and returns just a single index. Also, as it works on sorted arrays, the function name should be `searchsortednearest` to be consistent with Julia’s function names (I would expect `findnearest` to work on any array).

```julia
function searchsortednearest(a,x)
   idx = searchsortedfirst(a,x)
   if (idx==1); return idx; end
   if (idx>length(a)); return length(a); end
   if (a[idx]==x); return idx; end
   if (abs(a[idx]-x) < abs(a[idx-1]-x))
      return idx
   else
      return idx-1
   end
end

```

---

_[View the full topic](https://discourse.julialang.org/t/findnearest-function/4143)._
