排序JS数组的数组

时间:2017-10-19 03:27:17

标签: javascript arrays sorting

我有以下Javascript数组:

myArr = [[["One"],["First","Fourth","Third"]], 
         [["Two"],["First","Second","Third"]], 
         [["Three"],["First","Third"]], 
         [["One two"],["Fourth","Second","Third"]], 
         [["One three"],["Fourth","Third"]], 
         [["One two three"],["Second","Third"]]]; 

我需要这样排序,所以我得到:

[[["One"],["First","Fourth","Third"]], 
 [["One three"],["Fourth","Third"]], 
 [["One two"],["Fourth","Second","Third"]], 
 [["One two three"],["Second","Third"]], 
 [["Three"],["First","Third"]], 
 [["Two"],["First","Second","Third"]]]

我假设我可以使用myArr.sort()并获得正确排序的数组。 它适用于平面阵列,但不适用于嵌套数组。当我使用myArr.sort()时,我得到:

[[["One three"],["Fourth","Third"]], 
 [["One two three"],["Second","Third"]], 
 [["One two"],["Fourth","Second","Third"]], 
 [["One"],["First","Fourth","Third"]], 
 [["Three"],["First","Third"]], 
 [["Two"],["First","Second","Third"]]]

这对我来说毫无意义。 JS排序如何得到结果?我如何得到我需要的结果。

1 个答案:

答案 0 :(得分:3)

丑陋的方式:

myArr.sort((a, b) => (a[0][0]).localeCompare(b[0][0]))

基本上你想要将每个数组的第一个元素与彼此的

进行比较

myArr = [[["One"],["First","Fourth","Third"]], 
         [["Two"],["First","Second","Third"]], 
         [["Three"],["First","Third"]], 
         [["One two"],["Fourth","Second","Third"]], 
         [["One three"],["Fourth","Third"]], 
         [["One two three"],["Second","Third"]]];
         
const sorted = myArr.sort((a, b) => (a[0][0]).localeCompare(b[0][0]));

console.log(sorted);