JSFiddle - React, Tailwind, and code Playground
HTML
Values: <input type="text" name="values" value="0, 65, 131, 196, 259, 323, 388, 453, 517" id="values" /> <br />
Search : <input type="text" name="search" value="132" id="search" /> <br />
<button id="go">Go!</button> <br />
Result: <span id="result"></span>
CSS
#values, #search {
width: 80% ;
height: 25px ;
margin-bottom: 5px ;
}
JavaScript
var values = [0, 65, 131, 196, 259, 323, 388, 453, 517]
function closest (arr, x) {
/* lb is the lower bound and ub the upper bound defining a subarray or arr. */
var lb = 0,
ub = arr.length - 1 ;
/* We loop as long as x is in inside our subarray and the length of our subarray is greater than 0 (lb < ub). */
while (ub - lb > 1) {
var m = parseInt((ub - lb + 1) / 2) ; // The middle value
/* Depending on the middle value of our subarray, we update the bound. */
if (arr[lb + m] > x) {
ub = lb + m ;
}
else if (arr[lb + m] < x) {
lb = lb + m
}
else {
ub = lb + m ; ub = lb + m ;
}
}
/* After the loop, we know that the closest value is either the one at the lower or upper bound (may be the same if x is in arr). */
var clst = lb ;
if (Math.abs(arr[lb] - x) > Math.abs(arr[ub] - x)) {
clst = ub ;
}
return clst ; // If you want the value instead of the index, return arr[clst]
}
document.getElementById("go").onclick = function () {
var values = document.getElementById('values').value.split(',') ;
var array = [] ;
for (var i = 0 ; i < values.length ; ++i) { array.push(parseInt(values[i])) ; }
var search = parseInt(document.getElementById('search').value) ;
var clst = closest (array, search) ;
document.getElementById ('result').innerHTML = 'Values[' + clst + '] = ' + array[clst] ;
}
document.getElementById("search").onkeypress = function (e) {
if (e.keyCode == 13) {
document.getElementById("go").click () ;
}
}