DiD
DiD

Reputation: 77

Sorting multi dimensional array by 2 columns - JavaScript

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.

Upvotes: 1

Views: 2520

Answers (1)

robbmj
robbmj

Reputation: 16526

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

Upvotes: 5

Related Questions