I have the following function:
(function(){
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
var _array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
_number = 155;
return closest (_number, _array);
})()
Result is 162
In this array I want to show the closest index to the result!
The result should be number 4
You could store the index and return this value.
function closest(num, arr) {
var curr = arr[0],
diff = Math.abs(num - curr),
index = 0;
for (var val = 0; val < arr.length; val++) {
let newdiff = Math.abs(num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
index = val;
}
}
return index;
}
var array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
number = 155;
console.log(closest(number, array));