Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: sort 2D array at first by second column desc, then by first column asc

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.

like image 357
Ludus H Avatar asked Jul 03 '13 18:07

Ludus H


1 Answers

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);
like image 198
Joseph Myers Avatar answered Sep 20 '22 11:09

Joseph Myers