![](/img/trans.png)
[英]How to sort one array based on how another gets sorted? (Javascript)
[英]is it possible to sort a sorted array based on another object in javascript?
我正在按类型对这种类型的数组进行排序:
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;
}
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,则流派相等,因此我们将根据专辑数量进行比较。
这是0取...而是由OR运算符提供的...
当然,在完成对第一个数组的任何操作之后。 假设您不想修改第一个数组,则可以使用slice进行复制。 然后您可以按专辑编号排序。 让我知道这是否有帮助
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 } ]; var sortedAlbumNumber = bands.slice(); sortedAlbumNumber.sort((a, b) => a['albums'] - b['albums']); console.log(sortedAlbumNumber);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.