【问题标题】:Get the id of the nearest coordinate object获取最近的坐标对象的id
【发布时间】:2020-08-18 21:42:02
【问题描述】:

我正在使用answer in the example 来查找最近的对象坐标。如果例如,我如何找到距var points 最近的点的index最近的点是{x: 12, y: 18},然后是index = 1

如果可以保存该步骤,我想避免使用额外的 indexOf()。代码是:

var points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

function d(point) {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

var closest = points.slice(1).reduce(function(min, p) {
  if (d(p) < min.d) min.point = p;
  return min;
}, {point: points[0], d:d(points[0])}).point;

console.log(closest);

【问题讨论】:

  • id 是什么意思?我只看到坐标...
  • 你的出身在哪里?
  • 另外,在减速器中,您总是将点与数组中的第一个点进行比较,因为您从未更改累加器的 d 属性,我不确定这是否是您的意图。
  • 我现在是不是更清楚了@Titus。对不起,如果我之前写错了

标签: javascript


【解决方案1】:

您可以先将数组映射到还包含索引的对象数组:

const points = [
  {x: 10, y: 20},
  {x: 12, y: 18},
  {x: 20, y: 30},
  {x: 5, y: 40},
  {x: 100, y: 2}
];

const distance = (point) => {
  return Math.pow(point.x, 2) + Math.pow(point.y, 2);
}

const result = points
     .map((point, index) => ({ point, index }))
     .reduce((a, b) => distance(a.point) < distance(b.point) ? a : b);
     
console.log(result);

【讨论】:

  • 抱歉编辑,只是想让它可以运行,而是稍微更改了代码(删除了目标,因为它在原始函数中不存在)并且只有在我点击应用后才实现。如果您认为这违背了您的意图,请随时将其还原:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2019-04-14
  • 2021-09-28
  • 2012-03-31
  • 1970-01-01
相关资源
最近更新 更多