0 votes
93 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 263 views
0 votes
0 answers 81 views
0 votes
0 answers 44 views
0 votes
1 answer 263 views
0 votes
0 answers 45 views
0 votes
2 answers 281 views
0 votes
1 answer 629 views
+1 vote
0 answers 83 views
0 votes
0 answers 40 views
0 votes
0 answers 41 views

580 questions

482 answers

85 comments

1.7k users

Dosvak IBM BPM /BAW Products, Download Evaluation
Process & Performance Tools Process & Performance Tools
Code Analyzer Code Analyzer
UI Toolkit UI Toolkit
Integration Monitoring Integration Monitoring
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
...