简体   繁体   English

在javascript中按子数组值对数组排序

[英]Sorting arrays by subarray value in javascript

I have an array of arrays in javascript with a distance (integer, whole number) value. 我在javascript中使用距离(整数,整数)值组成的数组数组。 I am trying to sort them, but I can't seem to get this to work. 我正在尝试对它们进行排序,但似乎无法使它正常工作。

nodes = [[{distance:15}],[{distance:123}],[{distance:2}]];

function sortNodes(a,b) {
   if (a.distance < b.distance)
     return -1;
   if (a.distance > b.distance)
     return 1;
     return 0;
   }
console.log(nodes.slice(0).sort(sortNodes));

Need some direction on what is happening here and why. 需要有关这里发生的情况以及原因的一些指导。

You need to do return a[0].distance - b[0].distance; 您需要return a[0].distance - b[0].distance; this is because: 这是因为:

  1. distance is a integer type so you do not need to compare that and return 1 , -1 or 0 using comparison operator. distance是一个整数类型,因此您不需要比较它并使用比较运算符返回1-10
  2. You have array of arrays with one object inside the nested array so use [0] to get that object inside parameter a and b . 您在嵌套数组内部有一个对象数组,因此请使用[0]在参数ab获取该对象。

 var nodes = [ [{ distance: 15 }], [{ distance: 123 }], [{ distance: 2 }] ]; function sortNodes(a, b) { return a[0].distance - b[0].distance; } console.log(nodes.slice(0).sort(sortNodes)); 

The comparator function that is passed to the sort() function takes the values from the array. 传递给sort()函数的比较器函数从数组中获取值。

So, as you have mentioned that you have an array of arrays , the arguments of the comparator function would be arrays. 因此,正如您提到的那样,您有一个数组数组 ,比较器函数的参数将是数组。

Thus, you can use a[0] and b[0] to access the objects. 因此,您可以使用a[0]b[0]访问对象。

Here is the code: 这是代码:

nodes = [[{ distance: 15 }], [{ distance: 123 }], [{ distance: 2 }]];

function sortNodes(a, b) {
    if (a[0].distance < b[0].distance) return -1;
    if (a[0].distance > b[0].distance) return 1;
    return 0;
}
console.log(nodes.slice(0).sort(sortNodes));

Here is nice de-structuring example: 这是一个很好的解构示例:

nodes = [[{ distance: 15 }], [{ distance: 123 }], [{ distance: 2 }]];

function sortNodes([a], [b]) {
    return a.distance - b.distance
}
console.log(nodes.slice(0).sort(sortNodes));

This will also work: 这也将起作用:

nodes = [[{distance:15}],[{distance:123}],[{distance:2}]];

function sortNodes(a,b) {
    return a[0].distance > b[0].distance;
}
console.log(nodes.slice(0).sort(sortNodes));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM