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
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
2 Answers
Reset to default 3Here is a more straightforward solution (not optimal):
- find the difference between the number and the numbers in the array
- find the minimum in the new array of differences
- Now find the index of that minimum
var _array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362],
_number = 155;
// closest index?
const diffArr = _array.map(x => Math.abs(_number - x));
const minNumber = Math.min(...diffArr);
const index = diffArr.findIndex(x => x === minNumber);
console.log('Result index', index);
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));
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745332786a4622961.html
评论列表(0条)