# 如何按列值对二维数组排序？-问答-阿里云开发者社区-阿里云

## 如何按列值对二维数组排序？

[12, AAA] [58, BBB] [28, CCC] [18, DDD] 排序时应如下所示：

[12, AAA] [18, DDD] [28, CCC] [58, BBB] 因此，基本上，按第一列排序。

JavaScript 前端开发

• 保持可爱mmm
2020-02-08 21:48:05

站在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测试的完整脚本-使用Google Apps脚本。

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"], ]" */

}

0 0

+ 订阅