[英]Numeric sort on an array with javascript
I have this array : 我有这个数组:
[ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]
and I would like to have : 我想拥有:
[ [ 11, 'g' ], [ 9, 'e' ], [ 9, 'h' ], [ 3, 'i' ], [ 2, 'b' ], [ 1, 'a' ], [ 1, 'd' ], [ 1, 'f' ] ]
How can I do that with javascript please ? 请问如何使用javascript做到这一点?
I tried sort()
, I also tried with sort(compare)
with : 我尝试了sort()
,我也尝试了sort(compare)
与:
function compare(x, y) {
return x - y;
}
You can use .sort()
with Array Destructuring
like this: 您可以将.sort()
与Array Destructuring
.sort()
结合使用,如下所示:
function compare([a], [b]) {
return b - a;
}
Demo: 演示:
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; }
In case first elements match, you can sort based on 2nd element as well: 如果第一个元素匹配,则也可以基于第二个元素进行排序:
function compare([a, c], [b, d]) {
return (b - a) || c.localeCompare(d)
}
Demo: 演示:
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 }
You need to compare the first element in the nested array since you want to sort based on that number. 您需要比较嵌套数组中的第一个元素,因为您要基于该数字进行排序。
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);
In case you want to sort based on second element(secondary sorting in case the first element is same) then use String#localeCompare
method for comparing. 如果要基于第二个元素进行排序(如果第一个元素相同,则进行第二次排序),然后使用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);
Compare the elements based on their first element, which is the number. 根据元素的第一个元素(即数字)比较元素。
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)
Use sort
to compare first element and if first element is same then compare the second element . 使用sort
比较第一个元素,如果第一个元素相同,则比较第二个元素 。
arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) )
Demo 演示版
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.