Javascript按子数组对数组数组进行排序

标签 javascript arrays sorting

如何按第二个元素对数组数组进行排序,该元素也是仅包含一个元素的数组?

例如下面的数组

array = [
    ["text", ["bcc"], [2]],
    ["text", ["cdd"], [3]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [5]],
    ["text", ["d11"], [4]]
];

应按如下方式排序:
sorted_array = [
    ["text", ["aff"], [1]],
    ["text", ["bcc"], [2]],
    ["text", ["cdd"], [3]],
    ["text", ["d11"], [4]],
    ["text", ["zaa"], [5]]
];

最佳答案

您应该使用 .sort()接受 callback 的方法功能。

此外,您必须使用 .localeCompare比较两个 strings 的方法.

array = [
    ["text", ["bcc"], [1]],
    ["text", ["cdd"], [1]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [1]],
    ["text", ["d11"], [1]]
];
var sortedArray=array.sort(callback);
function callback(a,b){
  return a[1][0].localeCompare(b[1][0]);
}
console.log(sortedArray);

关于Javascript按子数组对数组数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251333/

相关文章:

c# - 作为多种类型的高效数组访问

c++ - 是否可以将 std::sort 与带有额外参数的排序函数一起使用?

Python sort and sorted -- 列表的列表如何精确排序?

javascript - 如何使用.ajax查询多个GitHub url,然后对结果进行排序?

javascript - 错误 : No QueryClient set, 使用 QueryClientProvider 设置一个

javascript - 在 Canvas 上变换会导致奇怪的行为

javascript - 在 NodeJS 中使用 mongo+mongoose 交换值的函数

php - mysql_fetch_array()期望参数1是资源,给定对象

javascript - 用于在右侧显示 yAxis 值的额外工具提示

javascript - 如何使用 jquery 或 java 脚本获取 <option> some value</option> 标记之间的文本 "ONLY ONCE"?