简体   繁体   中英

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]]

I would like to sort it by the X value, and keep the x,y values paired.

I searched the site for multidimentional sorting and found threads like these where the sort function is modified like so:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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