【问题标题】:sort 2 array's with objects of coordinates to get a list of which are closest to each-other使用坐标对象对 2 个数组进行排序,以获得彼此最接近的列表
【发布时间】:2021-09-10 03:00:26
【问题描述】:

我有 2 个带有坐标对象的数组。例如:

  const coordinates = [
    { x: 2, y: 6 },
    { x: 14, y: 10 },
    { x: 7, y: 10 },
    { x: 11, y: 6 },
  ];
  const coordinates2 = [
    { x: 8, y: 9 },
    { x: 25, y: 11 },
    { x: 2, y: 11 },
    { x: 7, y: 8 },
  ];

我想做一个排序函数,它会返回彼此最接近的。

我尝试了多种方法,但无法弄清楚。 接受任何解决方案。可能将 1 排序到另一个或同时排序。

这是我想要达到的目标:

result array 1[
    { x: 2, y: 6 },
    { x: 14, y: 10 },
    { x: 7, y: 10 },
    { x: 11, y: 6 },
  ];
  result array 2 = [
    { x: 2, y: 11 }, // beceause it is closest to {x: 2,y: 6}
    { x: 25, y: 11 }, // beceayse it is closest to {x: 14,y: 10},
    { x: 7, y: 8 }, // beceause it is closest to { x: 7, y: 10 }
    { x: 8, y: 9 }, // beceause it is closest to {x: 11,y: 6} after x: 7, y:10 but x:7, y:8 is even closer
  ];

^ 结果可能不同。但我想要他们之间最有效的距离。

查看坐标 a 和坐标 b 的距离的公式如下: 距离=√((x1-x2)²+(y1-y2)²)。

如果有人有想法或提示,请告诉我!

【问题讨论】:

  • 不清楚你在问什么。您能否举例说明您从上述数据中寻找的结果?目前尚不清楚您是否想要 A) {1} 中的一个点和 {2} 中最近的一个点,或者 B) {1} 中的每个点以及 {2} 中最接近它的每个点,或 C) {2} 中的每个点以及 {1} 中最靠近它的每个点,或者...?
  • 当然!我将编辑消息。

标签: javascript arrays sorting object filter


【解决方案1】:

您可以通过从第二个数组获取最近的坐标来映射第一个数组。

const
    getClosest = ({ x, y }, data) => data.reduce((a, b) => Math.hypot(x - a.x, y - a.y) < Math.hypot(x - b.x, y - b.y) ? a : b),
    coordinates = [{ x: 2, y: 6 }, { x: 14, y: 10 }, { x: 7, y: 10 }, { x: 11, y: 6 }, { x: 6, y: 2 }],
    coordinates2 = [{ x: 8, y: 9 }, { x: 25, y: 11 }, { x: 2, y: 11 }, { x: 18, y: 21 }, { x: 7, y: 8 }],
    pairs = coordinates.map(o => [o, getClosest(o, coordinates2)]);

console.log(pairs);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 感谢这个例子!将尝试对此进行一些编辑以使其正常工作。但问题是我不想重复。也许可以做这样的事情
猜你喜欢
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 1970-01-01
  • 2012-04-30
相关资源
最近更新 更多