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.

3

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is there no other way to solve this without using the JSON stringify? My program doesn't use JSON
@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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.