用Javascript对数组中的子数组按照子数组排序

4

如何按第二个元素排序数组的数组,第二个元素是仅含一个元素的数组?

例如,下面这个数组:

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

我看到这里有三个数组级别。如果它是单值,为什么子元素 'bcc' 在数组中?可能它可能有更多的值吗? - Khaleel
1
你想用 ['bcc'] 还是数字 [2] 进行排序? - Nina Scholz
@NinaScholz 我需要根据每个数组的第二个元素按字母顺序对数组进行排序。 - Valip
数组是从零开始的,你的第二个元素是什么? - Nina Scholz
1
['bcc'] - Valip
6个回答

2
你可以这样使用sort()方法。

var array = [
    ["text", ["bcc"], [1]],
    ["text", ["cdd"], [1]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [1]],
    ["text", ["d11"], [1]]
];

var result = array.sort((a, b) => a[1][0].localeCompare(b[1][0]))
console.log(result)


如果你想根据数组的所有元素进行排序,有没有快捷方式? - gjonte

2

您应该使用接受回调函数的.sort()方法。

此外,您还必须使用.localeCompare方法来比较两个字符串

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


2
你可以使用 String#localeCompare 来对嵌套元素进行排序。

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

array.sort(function (a, b) {
    return a[1][0].localeCompare(b[1][0]);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


2
你可以通过在数组排序函数中传递比较的子级数组来实现这一点。
array = [
    ["text", ["bcc"], [1]],
    ["text", ["cdd"], [1]],
    ["text", ["aff"], [1]],
    ["text", ["zaa"], [1]],
    ["text", ["d11"], [1]]
];

function Comparator(a, b) {
   if (a[1] < b[1]) return -1;
   if (a[1] > b[1]) return 1;
   return 0;
}

array = array.sort(Comparator);
console.log(array);

希望能够帮到你。

1

(仅适用于现代JavaScript引擎)

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

0

你可以做:

array.sort(function(a, b) { 
    if (a[1][0] > b[1][0])
        return 1;
    else if (a[1][0] < b[1][0])
        return -1;
    return 0; 
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接