function sortByCol(arr, colIndex){
arr.sort(sortFunction)
function sortFunction(a, b) {
a = a[colIndex]
b = b[colIndex]
return (a === b) ? 0 : (a < b) ? -1 : 1
}
}
// Usage
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']]
sortByCol(a, 0)
console.log(JSON.stringify(a))
// "[[12,"AAA"],[18,"DDD"],[28,"CCC"],[58,"BBB"]]"
站在 Charles-clayton 和@vikas-gautam 的肩膀上,我添加了字符串测试,如果一个列像 OP 中一样有字符串,那么就需要这个测试。
return isNaN(a-b) ? (a === b) ? 0 : (a < b) ? -1 : 1 : a-b ;
测试 isNaN(a-b)确定字符串是否不能被强制为数字。如果他们可以,那么 a-b测试是有效的。
注意,对混合类型的列进行排序总是会得到有趣的结果,因为严格的相等测试 (a === b)总是返回 false。
在这里看 MDN
这是 Logger 测试的完整脚本-使用 GoogleApps 脚本。
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"],
]"
*/
}
Solution vary depend on column value is numeric or string.
To sort by first column if value is numeric,
array.sort( (a, b) => a[0] - b[0]);
To sort by second column if value is numeric,
array.sort( (a, b) => a[1] - b[1]);
To sort by first column if value is string/letter,
array.sort( function(a, b) {
const nameA = a[0].toUpperCase(); // to avoid case while sort
const nameB = b[0].toUpperCase();
if(nameA > nameB)
return 1;
else if(nameB > nameA)
return -1;
else
return 0;
})