Javascript根据条件对2D数组进行排序

Javascript根据条件对2D数组进行排序,javascript,Javascript,我在计算点到原点的距离。这是一个基本的数学计算:math.sqrt math.powx-0,2+math.powy-0,2 对于测试,我有以下几点:点=[[1,3],-2,2]]。我想根据到原点的最小距离对其进行排序 我的代码: points.sort((a,b) => { const d1 = Math.sqrt( Math.pow(a[0], 2) + Math.pow(a[1], 2) ); const d2 = Math.sqrt( Math.po

我在计算点到原点的距离。这是一个基本的数学计算:math.sqrt math.powx-0,2+math.powy-0,2

对于测试,我有以下几点:点=[[1,3],-2,2]]。我想根据到原点的最小距离对其进行排序

我的代码:

points.sort((a,b) => {
        const d1 = Math.sqrt( Math.pow(a[0], 2) + Math.pow(a[1], 2) ); 
        const d2 = Math.sqrt( Math.pow(b[0], 2) + Math.pow(b[1], 2) ); 
        return d1 <= d2 ? a-b : b-a; 
});

console.log(points);

日志显示:[[1,3],-2,2]]2D数组未更改。排序函数中的计算是正确的。我不确定它为什么不起作用。

您需要计算距离的增量

var points=[[1,3],-2,2]]; points.sorta,b=>{ 常量d1=Math.sqrtMath.powa[0],2+Math.powa[1],2; constd2=Math.sqrtMath.powb[0],2+Math.powb[1],2; 返回d1-d2; };
控制台。对数点 你需要计算距离的增量

var points=[[1,3],-2,2]]; points.sorta,b=>{ 常量d1=Math.sqrtMath.powa[0],2+Math.powa[1],2; constd2=Math.sqrtMath.powb[0],2+Math.powb[1],2; 返回d1-d2; };
控制台。对数点;很抱歉,我不清楚排序方法是如何工作的。你能解释一下为什么我需要取delta吗?我想我没有得到需要在sort方法中返回的内容来对数据进行排序array@myTest532myTest532,也许你先看看这里:。回调的预期结果应该返回一个小于零的值,如果第一个值小于第二个值,则相同的值为零,所有其他值都大于零。我不清楚排序方法是如何工作的。你能解释一下为什么我需要取delta吗?我想我没有得到需要在sort方法中返回的内容来对数据进行排序array@myTest532myTest532,也许你先看看这里:。如果第一项小于第二项,则回调的预期结果应返回一个小于零的值,对于相同的项,返回一个小于零的值,对于所有其他项,返回一个大于零的值。