Javascript 在具有多个关键点的对象数组中查找最近的数字

Javascript 在具有多个关键点的对象数组中查找最近的数字,javascript,arrays,reduce,Javascript,Arrays,Reduce,我不是在处理一个简单的数字数组,我需要数字的上下文,即它是起点还是终点 我对如何计算哪个数字最接近某个特定数字感到困惑 const dataStructure = [{ uid: "123", startTime: 2, endTime: 6 }, { uid: "345", startTime: 9, endTime: 15 }] 我在拖动时跟踪节点的坐标,向左移动时,要计算的数字是其x坐标,向右移动时,我跟踪x坐标加上宽度。无

我不是在处理一个简单的数字数组,我需要数字的上下文,即它是起点还是终点

我对如何计算哪个数字最接近某个特定数字感到困惑

const dataStructure = [{
  uid: "123",
  startTime: 2,
  endTime: 6
}, {
  uid: "345",
  startTime: 9,
  endTime: 15
}]
我在拖动时跟踪节点的坐标,向左移动时,要计算的数字是其
x
坐标,向右移动时,我跟踪
x
坐标加上宽度。无论哪种方式,都会产生一个数字,我试图评估哪个点最接近我的数字。它可以是开始时间,也可以是结束时间

但是我需要知道它是否是开始/结束,以及匹配元素的uid

我试图在脑子里把减速机的逻辑放在一起,但还没弄清楚

const updatingTime = 6.7;

// TODO: Out of the two elements, which one is the closest, and which edge is the closest i.e start or end?
dataStructure.reduce((acc: any, curr: any) => {
  const lastEnd = acc.endTime;
  const lastStart = acc.startTime;
  const currEnd = curr.endTime;
  const currStart = curr.startTime;

  // find the node with either start or end closest to 6.7
  // also return key that was the best match i.e startTime/endTime

  return curr;
});

// if our number is 6.7 then uid: "123" is our answer with "end" being the edge

通过查找开始时间和结束时间之间的最小差值,可以找到最小距离

const数据=[
{uid:“123”,开始时间:2,结束时间:6},
{uid:“345”,开始时间:9,结束时间:15}
];
const findClosest=(数据,deltaFn,目标)=>
数据减少((上一个,当前)=>
deltaFn(当前,目标)-deltaFn(当前,目标)<0?当前:当前;
const minDiff=({startTime,endTime},target)=>
Math.min(Math.abs(startTime-target)、Math.abs(endTime-target));
常数最近=findClosest(数据,minDiff,6.7);
控制台日志(最近)

.as console wrapper{top:0;max height:100%!important;}
以下是我根据@bearacuda13简化解决方案的建议提出的解决方案

const closest = ({ key, items }: any) =>
  items.reduce((acc: any, curr: any) =>
    Math.abs(curr[key] - updatingTime) < Math.abs(acc[key] - updatingTime) ? curr : acc
  );

const findClosestStart = closest({ key: "startTime", items: closestEls });
const findClosestEnd = closest({ key: "endTime", items: closestEls });
const a = Math.abs(findClosestStart.startTime - updatingTime);
const b = Math.abs(findClosestEnd.endTime - updatingTime);

const which = a < b ? findClosestStart : findClosestEnd;

console.log({ which });
const最近=({key,items}:any)=>
项目.减少((会计科目:任何,货币:任何)=>
Math.abs(curr[key]-updatetime)

似乎这样做对性能和/或边缘情况不太确定。

似乎您试图在设计解决方案时走得太快了。Start simpler:编写一个函数,返回开始时间最近的元素(uid和距开始时间的距离)。然后,修改此方法以使其依赖于键。您可以使用键“endTime”和“startTime”调用这个更通用的方法,您的答案可以是这些调用结果的比较。好的一点,让我尝试一下,始终是:
dataStructure[i]。start
dataStructure[0]。end
dataStructure.length==2
?当我在这个代码库上迭代时,长度最终可以是n。在视频编辑时间线内捕捉到的检测元素。所以在大多数情况下,它会检查上面的一个元素和下面的一个元素。决定最近的边以及最适合捕捉到的边。我可以看到一个时间,它会在上面和下面查看多个轨迹,这是一个重叠的结构,如
[{uid:“123”,开始时间:2,结束时间:9},{uid:“345”,开始时间:6,结束时间:15}]
可能吗?“代码”> { uID:“123”,“启动时间:2”,“结束时间”:3 },{uID:“345”,“开始时间:5,结束时间:6 }”/<代码>和“更新时间<代码> 4 < /COD>(更新两点中间的时间))的预期结果是什么?这看起来不错,尝试一下,可能比我想出的更好。我很好奇这是否比我在下面发布的有什么优势?它工作得很好,我需要做一个小的修改,并返回我们需要捕捉到reduce函数内部的哪个边。谢谢分享:)