5

I have so called 2D array called myarr with dozen rows and 2 column. Its contents is as follows:

myarr[0][0]='John'
myarr[0][1]=48
myarr[1][0]='Ann'
myarr[1][1]=36
myarr[2][0]='Sean'
myarr[2][1]=18
...

And I would like to sort it by second column first descending, then by first column ascending, like this one:

John 48
Ann 36
Bob 36
Carl 36
Sean 18
Dean 17 ..

By using JavaScript and I tried something like this:

myarr.sort(function(a, b){
    a = a[1]+a[0];
    b = b[1]+b[0];
    return a == b ? 0 : (a > b ? 1 : -1)
})

But this way sort by column 2 asc (0 - 85) then by column 1 asc (A - Z). Where I made error? Thank you.

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Ludus H
  • 239
  • 2
  • 15
  • possible duplicate of [Javascript, how do you sort an array on multiple columns?](http://stackoverflow.com/questions/2784230/javascript-how-do-you-sort-an-array-on-multiple-columns) – tuespetre Jul 03 '13 at 19:12

1 Answers1

11

Update/note: this is a great compact sorting function for your situation that also supports strings with non-ASCII characters. I would consider this to be an "improvement" to my answer, only at the cost of being less easy to understand except to someone who knows what is going on:

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

Original suggested answer: This code will take the data you gave (randomized) and produce the output sorted as you desired.

myarr = [
['Dean', 17],
['John', 48],
['Ann', 36],
['Sean', 18],
['Bob', 36],
['Carl', 36]
];

myarr.sort(
function(a,b) {
if (a[1] == b[1])
return a[0] < b[0] ? -1 : 1;
return a[1] < b[1] ? 1 : -1;
}
);

alert(myarr);
Joseph Myers
  • 6,434
  • 27
  • 36
  • 1
    thank you man, this works as I wanted. I tried some combination but never this one you wrote. Can you please direct my for source to better understand it? – Ludus H Jul 03 '13 at 19:29
  • Yes, like this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Joseph Myers Jul 03 '13 at 19:30