Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
and what did you try? –  Nicholas Kyriakides Mar 10 at 16:39
1  
    
possible duplicate of Javascript: Sort Multidimensional Array –  Pete Mar 11 at 2:11

1 Answer 1

up vote 2 down vote accepted

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

share|improve this answer
    
Is there no other way to solve this without using the JSON stringify? My program doesn't use JSON –  DiD Mar 11 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 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 at 21:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.