0

Im wokring on a bit of functionality that works a lot with multidimensional arrays. What I would like to do is sort by the first value then sort by the second value while keeping the first value sorted. See example:

arrayToSort = [[1,5],[1,3],[1,2],[1,6],[2,6],[1,9],[1,11]];

I would like to sort this so it returns

[[1,2],[1,3],[1,5],[1,6],[1,9],[1,11],[2,6]];

I have created* a function to sort the array by the first value using the function below but im unsure how exactly i can achieve the above.

function sortOne(cards){
    arr = cards.sort(function(a,b) {
        return a[0] > b[0];
    });
    return arr;
}

*source: How to sort 2 dimensional array by column value?

Community
  • 1
  • 1
Glen Robson
  • 908
  • 2
  • 19
  • 42
  • Notice that your current comparison function is extremely inconsistent, it never returns a negative value. – Bergi Jun 06 '14 at 08:27
  • @Bergi My array will never contain negative values so this is fine. – Glen Robson Jun 06 '14 at 08:34
  • @GlenRobson: No, it's not about the values. If `a` is smaller than `b`, then the comparison must return a negative value (`-1`). Check [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)! – Bergi Jun 06 '14 at 08:37
  • @Bergi I didnt write this code you may want to take it up with the person that did: http://stackoverflow.com/a/16096900/1531541 – Glen Robson Jun 06 '14 at 08:43
  • @GlenRobson in the question you write "I have created a function to sort the array" and as soon as there is a flaw you "credit" your "source". TT – Winchestro Jun 06 '14 at 09:07
  • @Winchestro I apologise, by created i did not mean i personally wrote that function. – Glen Robson Jun 06 '14 at 09:30

1 Answers1

4

Sort by the first value, then by the second:

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

It's just two (standard number) comparisons, linked by the || operator which returns the right operand when the first is 0.

See here for a generic comparison function that deals with arrays of arbitrary length, not only tuples.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375