# How to find the closest value in an array

**URL:** <https://forum.kirupa.com/t/how-to-find-the-closest-value-in-an-array/247306>\
**Category:** Uncategorized\
**Created:** [December 21, 2007, 12:14am UTC](https://forum.kirupa.com/t/how-to-find-the-closest-value-in-an-array/247306 "2007-12-21T00:14:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![joeydigital](https://avatars.discourse-cdn.com/v4/letter/j/6bbea6/32.png) [@joeydigital](https://forum.kirupa.com/u/joeydigital)\
**Post date:** [December 21, 2007, 12:14am UTC](https://forum.kirupa.com/t/how-to-find-the-closest-value-in-an-array/247306/1 "2007-12-21T00:14:08Z")

</div>

All I’m trying to do is find a value in an array that’s closest to the value of my variable…

So if the value of myVar = 50;  
…and the array holds the values 25, 100, 150, etc.

I want to write a function that will be able to find the array element that’s closest to myVar, which would be the first element in the array (myArray[0]), since 25 would be the closest value to 50.

If anyone out there has any ideas, I’d really appreciate it…
