Nearest Number //JavaScript Repository
Description
Given an ordered numeric array and a number "X", retrieves the index of the nearest number to "X".
Created: 2008.03.14
Created: 2008.03.14
Code (Download)
//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/nearest-number [rev. #0]
function getNearestNumber(a, n){
if((l = a.length) < 2)
return l - 1;
for(var l, p = Math.abs(a[--l] - n); l--;)
if(p < (p = Math.abs(a[l] - n)))
break;
return l + 1;
}
Example (Example)
<script type="text/javascript">
//<![CDATA[
var array = [0, -3, 10, -10, 15];
//Must be sorted from the smallest to the highest
array = array.sort(function(a, b){
return a - b;
});
document.write(
"Array = [", array, "]<br />Indexes of the nearest numbers to:<br />",
"5 = ", getNearestNumber(array, 5), "<br />",
"9 = ", getNearestNumber(array, 9), "<br />",
"15 = ", getNearestNumber(array, 15), "<br />",
"-15 = ", getNearestNumber(array, -15), "<br />",
"-2 = ", getNearestNumber(array, -2)
);
//]]>
</script>
Help
- getNearestNumber(a: Array, n: Number): Integer
-
Finds the nearest number to the "n" argument in the array and retrieves its index, or -1 whenever the array is empty.
- a
- array of numbers *sorted* from the smallest to the highest
- n
- reference number
Rank (Votes: 57)
2.30