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

4
  • 1
    Possible duplicate of Grouped sorting on a JS array Commented May 29, 2017 at 14:35
  • 1
    How is the title related to the question? "sort based on another object" vs. "sort by multiple properties" Commented May 29, 2017 at 14:37
  • Possible duplicate of Javascript, how do you sort an array on multiple columns? Commented May 29, 2017 at 14:41
  • That's I what I really meant but I just find the right words earlier. Thank you so much. Commented May 29, 2017 at 14:46

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.