【发布时间】:2019-08-12 17:34:12
【问题描述】:
我尝试在数组中获取最接近的值索引。索引必须最接近 向上值,并且不依赖于顺序 - asc 或 desc
我目前正在使用返回最接近向上索引的函数,但数组必须是 asc(缺少 desc)。
function closestIndex(value, arr, from, to) {
from = (typeof from !== 'undefined') ? from : 0;
to = (typeof to !== 'undefined') ? to : arr.length;
if (from >= to) {
return to - 1;
}
var mid = Math.floor((from + to) / 2);
if (arr[mid] > value) {
return closestIndex(value, arr, from, mid);
}
return closestIndex(value, arr, mid + 1, to);
}
var arr = [10, 15, 20, 50, 100];
console.log(closestIndex(8, arr)); //index: -1
console.log(closestIndex(10, arr)); //index: 0
console.log(closestIndex(14, arr)); //index: 0
console.log(closestIndex(1000, arr)); //index: 4
我应该收到这些值:
//var arr = [100,50,20,15,10]; //same, just reversed values
//val: 8 = idx: 4
//val: 10 = idx: 4
//val: 14 = idx: 3
//val: 1000 = idx: -1
【问题讨论】:
-
当数组中的索引
5处没有元素时,为什么5是一个结果? -
基于什么你认为一个值(来自数组)接近输入值?
-
而二分查找只适用于已排序的数据集,如果有时升序有时降序,则未排序。
-
@Paulpro 如果你注意到了,整行移动 1 - 如果值小于第一个值,它返回 0 insted of -1 - 仅用于“我的”需要
标签: javascript arrays closest