gpt4 book ai didi

javascript - 使用javascript对数组进行数字排序

转载 作者:行者123 更新时间:2023-11-30 07:03:47 25 4
gpt4 key购买 nike

我有这个数组:

[ [ 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像这样:

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 }

关于javascript - 使用javascript对数组进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com