0 votes
831 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.2k views
0 votes
0 answers 390 views
0 votes
0 answers 250 views
0 votes
1 answer 1.1k views
0 votes
0 answers 803 views
0 votes
2 answers 976 views
+1 vote
0 answers 1.2k views
0 votes
1 answer 2.1k views
+1 vote
0 answers 585 views
0 votes
0 answers 294 views
0 votes
0 answers 542 views

634 questions

495 answers

97 comments

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