首页 > 解决方案 > 找到在NodeJS中找到对象列表的欧几里得距离的最佳方法

问题描述

我有一个如下的对象列表,需要针对列表中的所有项目找到 test_obj 的欧几里德距离。

object_list = [ [1,2,3],
                [10,20,30],
                [15,25,35],
                [20,30,40] ]

test_obj = [15,25,35]

我发现 numpy.linalg.norm() 在 python 中找到它。在 NodeJS 中是否有任何类似的方法或实用程序可以做同样的事情?

标签: node.jseuclidean-distance

解决方案


Node.js 有一个模块可以完成此任务:euclidean-distance

然后我们可以使用 array.map() 来获取从 test_obj 到 object_list 中每个项目的距离(反之亦然!),如下所示:

const distance = require('euclidean-distance')

object_list = [ [1,2,3],
                [10,20,30],
                [15,25,35],
                [20,30,40] ]

test_obj = [15,25,35]

let distances = object_list.map(obj => distance(test_obj, obj));
console.log("Distances:", distances);

推荐阅读