如何从数组中获得最接近的值
How to get nearest value from Array?
我有一个像这样的数组:
var array = [{top: 5, left: 50}, {top: 12, left: 44}, {top: 60, left: 11}]
我需要在这个数组中找到最接近top
和left
的,如果我知道:
var findNearest = {top:10, left:40}; //never be bigger than +5 (or lower than -5)
例如,在这种情况下,它应该返回第二个,因为top: 12
在我的findNearest
对象中接近top:10
,并且差异不大于5。left也是一样
如何?
编辑
我的想法是创建for
循环并检查每个对象是否与我想要找到的对象具有相同的值。如果没有,重复for
循环,增加+1
的值。
my bad idea:
var increaseTop = true;
var increaseLeft = true;
function find(obj){
for(var i = 0; i < array.length; i++){
if(array[i].top == obj.top){
// found nearest .top, not increase by 1
increaseTop = false;
}
if(array[i].left == obj.left){
// found nearest .left, not increase by 1
increaseLeft = false;
}
}
// here repeat for loop if is increaseLeft OR increaseTop is true
// with increased values .top and .left
}
findNearest({top:10, left:40});
计算每段距离并得到最小值:
var array = [{top: 5, left: 50}, {top: 12, left: 44}, {top: 60, left: 11}]
var findNearest = getNearest({top:10, left:40}, array);
console.log(findNearest);
function getDistance(p1, p2) {
var a = p2.top - p1.top;
var b = p2.left - p1.left;
return Math.sqrt(a*a + b*b);
}
function getNearest(point, points) {
var min = Number.POSITIVE_INFINITY,
minIndex;
var dist;
for(var i = 0 ; i < points.length; i++) {
dist = getDistance(point, points[i]);
if(dist < min) {
min = dist;
minIndex = i;
}
}
return points[minIndex];
}
相关文章:
- 获取最接近的数组数
- JavaScript:如何在最接近值的关联数组中查找键
- 在 javascript 数组中搜索最接近的下一个值
- 按键查找数组中最接近的 2 个元素
- Kadane 的最大子数组算法是否适用于所有正整数数组?
- Javascript/jquery- 如何在数组中获取最接近的时间
- 从数组中获取最接近的数字匹配项,必须更低
- 如何使用 lodash 从数组中获取最接近目标的前两个数字
- javascript/查找数组中最接近的值
- 什么'这是在二维数组中找到最短数组的最佳方法
- 在Javascript中查找最接近所需值的数组条目
- 查找数组数组中最长数组的索引
- 查找最接近给定时间数组的时间
- Javascript在数组中找到最接近的数字,而不需要重复
- 从数组中获取最接近的数字
- Javascript在数组中找到最接近的数字
- 最接近数组的价格
- 如何从数组中获得最接近的值
- 我如何在数组中找到最接近的数字,而不用遍历
- 获取数组(JS)组合的最接近的值