简体   繁体   English

是否有可能基于JavaScript中的另一个对象对已排序的数组进行排序?

[英]is it possible to sort a sorted array based on another object in javascript?

I am sorting this type of array by genre: 我正在按类型对这种类型的数组进行排序:

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}
];

With this: 有了这个:

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;
}

As describe here But after sorting by genre, I also want to sort it by number of albums.Is it possible? 就像这里描述的那样但是在按流派排序之后,我还想按专辑的数量对它进行排序。 TIA 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;
}

I shortified your code to genreA.localeCompare(genreB). 我将您的代码简化为genreA.localeCompare(genreB)。 If it is 0, the genres are equal, and we'll therefore compare by the number of albums. 如果为0,则流派相等,因此我们将根据专辑数量进行比较。

This if 0 take ... instead is provided by the OR operator... 这是0取...而是由OR运算符提供的...

Sure, after you are done doing whatever you need to do with the first array. 当然,在完成对第一个数组的任何操作之后。 Assuming you don't want to modify your first array, you can make a copy by using slice. 假设您不想修改第一个数组,则可以使用slice进行复制。 Then you can sort by album number. 然后您可以按专辑编号排序。 Let me know if this helps 让我知道这是否有帮助

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM