简体   繁体   English

JS数组排序

[英]Sorting JS array of arrays

I have the following Javascript array:我有以下 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"]]]; 

I need this sorted so I get:我需要这个排序所以我得到:

[[["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"]]]

I assumed I could just use myArr.sort() and get the properly sorted array.我以为我可以只使用myArr.sort()并获得正确排序的数组。 It does work on a flat array but not on nested arrays.它确实适用于平面阵列,但不适用于嵌套阵列。 When i use myArr.sort() I get:当我使用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"]]]

This makes zero sense to me.这对我来说是零意义的。 How does JS sort get to that result? JS 排序是如何得到这个结果的? And how do I get the result I need.以及如何得到我需要的结果。

Ugly way:丑陋的方式:

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

Basically you want to compare the first element of each array to each other's基本上你想将每个数组的第一个元素与彼此的元素进行比较

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM