我有这样的数组:
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
在我的top:10
对象中靠近findNearest
,差异不大于5.左边相同的事情。
如何?
修改
我的想法是创建for
循环并检查每个对象是否具有与我想要查找的对象相同的值。如果不是,请使用增加的值for
重复+1
循环。
我的坏主意的例子:
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});
答案 0 :(得分:2)
只需计算每个距离并获得最小值:
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];
}