silent_coder14
silent_coder14

Reputation: 583

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

Upvotes: 0

Views: 64

Answers (2)

Rick
Rick

Reputation: 1055

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

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138477

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...

Upvotes: 1

Related Questions