是否可以根据 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);

最新更新