簡體   English   中英

使用javascript對數組進行數字排序

[英]Numeric sort on an array with javascript

我有這個數組:

[ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]

我想擁有:

[ [ 11, 'g' ], [ 9, 'e' ], [ 9, 'h' ], [ 3, 'i' ], [ 2, 'b' ], [ 1, 'a' ], [ 1, 'd' ], [ 1, 'f' ] ]

請問如何使用javascript做到這一點?

我嘗試了sort() ,我也嘗試了sort(compare)與:

function compare(x, y) {
  return x - y;
}

您可以將.sort()Array Destructuring .sort()結合使用,如下所示:

function compare([a], [b]) {
  return b - a;
}

演示:

 let a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; a.sort(compare); function compare([a], [b]) { return b - a; } console.log(a); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 


如果第一個元素匹配,則也可以基於第二個元素進行排序:

function compare([a, c], [b, d]) {
  return (b - a) || c.localeCompare(d)
}

演示:

 let a = [ [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ], [ 1, 'a' ] ]; a.sort(compare); function compare([a, c], [b, d]) { return (b - a) || c.localeCompare(d); } console.log(a); 
 .as-console-wrapper { max-height: 100% !important; top: 0 } 

您需要比較嵌套數組中的第一個元素,因為您要基於該數字進行排序。

function compare(x, y) {
  return y[0] - x[0];
}

 var data = [ [1, 'a'], [2, 'b'], [1, 'd'], [9, 'e'], [1, 'f'], [11, 'g'], [9, 'h'], [3, 'i'] ]; function compare(x, y) { return y[0] - x[0]; } data.sort(compare); console.log(data); 


如果要基於第二個元素進行排序(如果第一個元素相同,則進行第二次排序),然后使用String#localeCompare方法進行比較。

function compare(x, y) {
  return y[0] - x[0] || x[1].localeCompare(y[0]);
}

 var data = [ [2, 'b'], [1, 'd'], [9, 'e'], [1, 'f'], [1, 'a'], [11, 'g'], [9, 'h'], [3, 'i'] ]; function compare(x, y) { return (y[0] - x[0]) || x[1].localeCompare(y[1]); } data.sort(compare); console.log(data); 

根據元素的第一個元素(即數字)比較元素。

 var a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; a = a.sort((a,b) => { return b[0] - a[0] }); console.log(a) 

使用sort 比較第一個元素,如果第一個元素相同,則比較第二個元素

arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) )

演示版

 var arr = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]; arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) ); console.log(arr); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM