3

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.

0

3 Answers 3

5

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]; });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I guess that was pretty obvious!
2

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];
});

Comments

1

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

4 Comments

Maybe useful as a comment, but this answer is going to confuse somebody.
@Mathletics It's an answer - if the first element (x) is a single digit location.sort() works. How is that not a solution?
Some noob is going to read that, miss the part about single digits (not understanding that sort, by default, is a string compare, which is why that works), and end up asking another question that could be easily answered by reading MDN.
@Mathletics I've tried to make it more obvious - however I feel it's worth keeping there as it is much simpler to read and less code to manage (when possible to safely use)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.