1

I have a 2 dimensional array with different elements in it. I want to sort the array based on 2 different criteria. One being a string and the other an integer. Here is an example.

var arr = [
    ['ABC', 87, 'WHAT'], 
    ['ABC', 34, 'ARE'], 
    ['DEF', 13, 'YOU'], 
    ['ABC', 18, 'DOING'], 
    ['ABC', 34, 'DOING'],
    ['DEF', 24, 'TODAY']
];

I want to sort first by the first element and then by the second element.

robbmj
  • 16,085
  • 8
  • 38
  • 63
DiD
  • 77
  • 1
  • 11
  • and what did you try? – nicholaswmin Mar 10 '15 at 16:39
  • 1
    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) – James Montagne Mar 10 '15 at 16:39
  • possible duplicate of [Javascript: Sort Multidimensional Array](http://stackoverflow.com/questions/6993302/javascript-sort-multidimensional-array) – Pete Mar 11 '15 at 02:11

1 Answers1

5

It is fairly straight forward:

If the strings are equal, then break the tie by comparing the integer values, else return the result of localeCompare

var arr = [
  ['ABC', 87, 'WHAT'],
  ['ABC', 34, 'ARE'],
  ['DEF', 13, 'YOU'],
  ['ABC', 18, 'DOING'],
  ['ABC', 34, 'DOING'],
  ['DEF', 24, 'TODAY'],
  ['ABA', 18, 'TODAY'],
  ['ABA', 11, 'TODAY']
];

function doSort(ascending) {
    ascending = typeof ascending == 'undefined' || ascending == true;
    return function(a, b) {
       var ret = a[0].localeCompare(b[0]) || a[1] - b[1];
       return ascending ? ret : -ret;
    };
}

// sort ascending
arr.sort(doSort());
// sort descending
arr.sort(doSort(false));

Fiddle

robbmj
  • 16,085
  • 8
  • 38
  • 63
  • Is there no other way to solve this without using the JSON stringify? My program doesn't use JSON – DiD Mar 11 '15 at 18:49
  • @DiD `JSON.stringify` is only being used to display the sorted output, you can ignore it. The `doSort` function and `arr.sort(doSort());` call are all you really need. – robbmj Mar 11 '15 at 18:55
  • @DiD I made it a little easier for you. The only code you need is now all the code that is in the answer. But you can still check out the demo by clicking the link titled Fiddle. – robbmj Mar 11 '15 at 21:07