gpt4 book ai didi

javascript - 是否可以根据javascript中的另一个对象对已排序的数组进行排序?

转载 作者:行者123 更新时间:2023-12-03 04:13:07 25 4
gpt4 key购买 nike

我正在按类型对这种类型的数组进行排序:

const bands = [ 
{ genre: 'Rap', band: 'Migos', albums: 2},
{ genre: 'Pop', band: 'Coldplay', albums: 4, awards: 10},
{ genre: 'Pop', band: 'xxx', albums: 4, awards: 11},
{ genre: 'Pop', band: 'yyyy', albums: 4, awards: 12},
{ genre: 'Rock', band: 'Breaking zzzz', albums: 1}
{ genre: 'Rock', band: 'Breaking Benjamins', albums: 1}
];

这样:

function compare(a, b) {
// Use toUpperCase() to ignore character casing
const genreA = a.genre.toUpperCase();
const genreB = b.genre.toUpperCase();

let comparison = 0;
if (genreA > genreB) {
comparison = 1;
} else if (genreA < genreB) {
comparison = -1;
}
return comparison;
}

如描述here但是按流派排序后,我还想按专辑数量排序,可以吗? TIA

最佳答案

function compare(a, b) {
// Use toUpperCase() to ignore character casing
const genreA = a.genre.toUpperCase();
const genreB = b.genre.toUpperCase();

return genreA.localeCompare(genreB) || a.albums-
b.albums;
}

我将您的代码缩短为genreA.localeCompare(genreB)。如果为 0,则流派相等,因此我们将按专辑数量进行比较。

这个 if 0 take ... 相反是由 OR 运算符提供的...

关于javascript - 是否可以根据javascript中的另一个对象对已排序的数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44245014/

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