How to sort 2 dimensional array by column value? How to sort 2 dimensional array by column value? javascript javascript

How to sort 2 dimensional array by column value?


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;    }}


The best approach would be to use the following, as there may be repetitive values in the first column.

var arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];arr.sort(function(a,b) {    return a[0]-b[0]});


try this

//WITH FIRST COLUMNarr = arr.sort(function(a,b) {    return a[0] - b[0];});//WITH SECOND COLUMNarr = arr.sort(function(a,b) {    return a[1] - b[1];});

Note: Original answer used a greater than (>) instead of minus (-) which is what the comments are referring to as incorrect.