0 votes
1.1k 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 1.5k views
0 votes
0 answers 532 views
0 votes
0 answers 329 views
0 votes
1 answer 1.3k views
0 votes
0 answers 1.2k views
+1 vote
1 answer 1.4k views
0 votes
2 answers 1.5k views
0 votes
1 answer 2.4k views
+1 vote
0 answers 701 views
0 votes
0 answers 374 views
+1 vote
0 answers 1.3k views
0 votes
0 answers 799 views

635 questions

495 answers

98 comments

3.1k users

Join BPM Community Discord Channel

Welcome to BPM Tips Q&A, Community wiki/forum where you can ask questions and receive answers from other IBM BPM experts and members of the community. Users with 2000 points will automatically be promoted to expert level.
Created by Dosvak LLC
Our Youtube Channel
...