2017-02-15 129 views
2

如何通过第二个元素对数组进行排序?第二个元素也是只包含一个元素的数组?Javascript按子数组排序数组

例如,下面的数组

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

我在这里看到3级的数组。如果它是单个值,为什么孩子“密件抄送”是在阵列中。它可能有更多的价值吗? – Khaleel

+1

你想用'['bcc']'还是用数字[2]排序? –

+0

@NinaScholz我需要按照字母顺序对数组进行排序,具体取决于每个数组的第二个元素 – Valip

回答

2

您应该使用.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);

1

你可以这样做:

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

2

您可以用嵌套的元素进行排序。

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