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