0 votes
45 views
in Javascript API by

Sort an Array of Objects in JavaScript

Now let’s look at sorting an array of objects. Let’s take an array of band objects:

const bands = [
  { genre: 'Rap', band: 'Migos', albums: 2},
  { genre: 'Pop', band: 'Coldplay', albums: 4},
  { genre: 'Rock', band: 'Breaking Benjamins', albums: 1}
];

We can use the following compare function to sort this array of objects according to genre:

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

bands.sort(compare);

/* returns [
{ genre: 'Pop', band: 'Coldplay', albums: 4 },
{ genre: 'Rap', band: 'Migos', albums: 2 },
{ genre: 'Rock', band: 'Breaking Benjamins', albums: 1 }
] */

Please log in or register to answer this question.

Related questions

0 votes
1 answer 171 views
0 votes
0 answers 30 views
0 votes
0 answers 30 views
0 votes
1 answer 143 views
0 votes
0 answers 24 views
0 votes
2 answers 254 views
0 votes
1 answer 391 views
+1 vote
0 answers 44 views
0 votes
0 answers 27 views
0 votes
0 answers 277 views
0 votes
0 answers 25 views
...