How to sort 2 dimensional array by column value?

Alex picture Alex · Apr 19, 2013 · Viewed 175.8k times · Source

Can any one help me sort a 2 dimensional Array in JavaScript?

It will have data in the following format:

[12, AAA]
[58, BBB]
[28, CCC]
[18, DDD]

It should look like this when sorted:

[12, AAA]
[18, DDD]
[28, CCC]
[58, BBB]

So basically, sorting by the first column.

Cheers

Answer

jahroy picture jahroy · Apr 19, 2013

It's this simple:

var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];

a.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

I invite you to read the documentation.

If you want to sort by the second column, you can do this:

a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}