0

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

silent_coder14
  • 583
  • 2
  • 10
  • 38
  • 1
    Possible duplicate of [Grouped sorting on a JS array](https://stackoverflow.com/questions/16164078/grouped-sorting-on-a-js-array) – Zenoo May 29 '17 at 14:35
  • 1
    How is the title related to the question? "sort based on another object" vs. "sort by multiple properties" – Andreas May 29 '17 at 14:37
  • Possible duplicate of [Javascript, how do you sort an array on multiple columns?](https://stackoverflow.com/questions/2784230/javascript-how-do-you-sort-an-array-on-multiple-columns) – Andreas May 29 '17 at 14:41
  • That's I what I really meant but I just find the right words earlier. Thank you so much. – silent_coder14 May 29 '17 at 14:46

2 Answers2

1
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). If it is 0, the genres are equal, and we'll therefore compare by the number of albums.

This if 0 take ... instead is provided by the OR operator...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

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. 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);
Rick
  • 1,035
  • 10
  • 18