我正在按类型对这种类型的数组进行排序:
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/