简体   繁体   English

排序多维数组javascript

[英]sort multidimensional array javascript

I would like to sort a multidimensional array of doubles. 我想对多维数组进行排序。

The array looks like this : [[1,2],[2,3],[5,6],[8,9]] 数组看起来像这样:[[1,2],[2,3],[5,6],[8,9]]

I would like to sort it by the X value, and keep the x,y values paired. 我想按X值对其进行排序,并保持x,y值配对。

I searched the site for multidimentional sorting and found threads like these where the sort function is modified like so: 我在网站上搜索了多维分类,并找到了像这样的线程,其中sort函数被修改如下:

location.sort(function(a,b) {

  // assuming distance is always a valid integer
  return parseInt(a.distance,10) - parseInt(b.distance,10);

});

I'm not sure how to modify this function to work for me, however. 但是,我不知道如何修改此功能以便为我工作。

Just compare the array values - 只需比较数组值 -

var myarray =  [[1,2],[2,3],[5,6],[8,9]];

myarray.sort(function(a,b) { return a[0] - b[0]; });

You just need to compare the parts of a and b that you want to. 你只需要比较你想要的ab部分。 With numbers you can use their difference: 使用数字,您可以使用它们的区别:

location.sort(function(a, b){
    return a[0] - b[0];
});

Note that the array you provided already is sorted by the first value in each array. 请注意,您提供的数组已按每个数组中的第一个值排序。 If you want to sort in descending order instead you can do this: 如果您想按降序排序,则可以执行以下操作:

location.sort(function(a, b){
    return b[0] - a[0];
});

The safest way of achieving this is to do what you have in your question, but with numeric keys: 实现这一目标最安全的方法是在您的问题中执行您的操作,但使用数字键:

location.sort(function(a,b) { return a[0]-b[0]; })

If by some chance the first element of each child array is always a single digit : 如果有可能每个子数组第一个元素总是一个数字

location.sort(); 
//only works if first element in child arrays are single digit (0-9)
//as in the example: [[1,2],[2,3],[5,6],[8,9]]
//[[1,2],[22,3],[5,6],[8,9]] - will not work as 22 is not a single digit

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

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