Javascript 数组的排序
我有以下Javascript数组:Javascript 数组的排序,javascript,arrays,sorting,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"]
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排序是如何得到这个结果的?我怎样才能得到我需要的结果 丑陋的方式:
myArr.sort((a, b) => (a[0][0]).localeCompare(b[0][0]))
基本上,您希望将每个数组的第一个元素与其他元素进行比较
myArr=[[“一”]、[“第一”、“第四”、“第三”],
两个、第一个、第二个、第三个、,
[“三”]、[“第一”、“第三”],
[“一二”]、[“第四”、“第二”、“第三”],
[“一三”]、[“第四”、“第三”],
[[“一二三”]、[“第二”、“第三”]];
const sorted=myArr.sort((a,b)=>(a[0][0])。localeCompare(b[0][0]);
控制台日志(已排序)代码>尝试一下文档。这是有道理的。“通过将元素转换为字符串并以Unicode代码点顺序比较字符串,对元素进行排序”。数组转换为逗号分隔的字符串。因为在Unicode序列中,空格在逗号之前,所以单词之间用空格分隔的元素排在第一位。@david25272谢谢。这可能是我读过的最清楚的解释了。