如何按第二个元素对数组数组进行排序,该元素也是仅包含一个元素的数组?
例如下面的数组
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/