Standing on the shoulders of charles-clayton and @vikas-gautam, I added the string test which is needed if a column has strings as in OP.
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ;
The test isNaN(a-b)
determines if the strings cannot be coerced to numbers. If they can then the a-b
test is valid.
Note that sorting a column of mixed types will always give an entertaining result as the strict equality test (a === b)
will always return false.
See MDN here
This is the full script with Logger test - using Google Apps Script.
function testSort(){
function sortByCol(arr, colIndex){
arr.sort(sortFunction);
function sortFunction(a, b) {
a = a[colIndex];
b = b[colIndex];
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ; // test if text string - ie cannot be coerced to numbers.
// Note that sorting a column of mixed types will always give an entertaining result as the strict equality test will always return false
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
}
}
// Usage
var a = [ [12,'12', 'AAA'],
[12,'11', 'AAB'],
[58,'120', 'CCC'],
[28,'08', 'BBB'],
[18,'80', 'DDD'],
]
var arr1 = a.map(function (i){return i;}).sort(); // use map to ensure tests are not corrupted by a sort in-place.
Logger.log("Original unsorted:\n " + JSON.stringify(a));
Logger.log("Vanilla sort:\n " + JSON.stringify(arr1));
sortByCol(a, 0);
Logger.log("By col 0:\n " + JSON.stringify(a));
sortByCol(a, 1);
Logger.log("By col 1:\n " + JSON.stringify(a));
sortByCol(a, 2);
Logger.log("By col 2:\n " + JSON.stringify(a));
/* vanilla sort returns " [
[12,"11","AAB"],
[12,"12","AAA"],
[18,"80","DDD"],
[28,"08","BBB"],
[58,"120","CCC"]
]
if col 0 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[18,'80',"DDD"],
[28,'08',"BBB"],
[58,'120',"CCC"]
]"
if col 1 then returns "[
[28,'08',"BBB"],
[12,'11', 'AAB'],
[12,'12',"AAA"],
[18,'80',"DDD"],
[58,'120',"CCC"],
]"
if col 2 then returns "[
[12,'12',"AAA"],
[12,'11', 'AAB'],
[28,'08',"BBB"],
[58,'120',"CCC"],
[18,'80',"DDD"],
]"
*/
}