2017-02-15 14 views
2

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レベルの配列があります。それが単一の値であればなぜ子「bcc」が配列しているのか。より多くの値を持つ可能性がありますか? – Khaleel

+1

'['bcc']'や番号[2]でソートしたいですか? –

+0

@ NinaScholz各配列の2番目の要素に応じて、配列をアルファベット順にソートする必要があります。 – Valip

答えて

2

あなたはcallback機能を受け入れる.sort()メソッドを使用する必要があります。

stringsを比較するには、.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);

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