繁体   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