Sort Array Object

I have been digging into the Sort object array for many hours trying to fully understand it but in vain.

(After FCC site changed the exercise related to this matter and it disappeared from the curriculum. )

This is the code, I wrote it then I fixed it by reading MDN.


var bands = [ 

    { genre: 'Rap', band: 'Migos', albums: 2},

    { genre: 'Pop', band: 'Coldplay', albums: 4},

    { genre: 'Rock', band: 'Breaking Benjamins', albums: 1}

  ];																	



  bands.sort(function(a, b) {

    var campareA = bands.genre.toUpperCase();

    var campareB = bands.genre.toUpperCase();

    if (campareA > campareB) {

        return 1;

    }

    if (campareA < campareB) {

        return -1;

    }

    else 

        return 0 ;

});

The issue is that I could not understand why we use -1, 1 and 0.

Then how to execute this code and do the actual sorting?

  • You’re not using your a and b.
  • campareA and campareB are exactly the same because you set them to the same thing.
  • bands is an array, so it doesn’t have a genre property.
1 Like

We use those to tell the engine if the object is of a lower order, higher order, or the same. It’s just a shorthand code developers have used to mean (true, false, null)

This is essentially what the code is saying

if (campareA > campareB) {

        return 1; // true -> 'a' should be placed in a higher index  than 'b'

}

if (campareA < campareB) {

   return -1; // false -> 'a' should be placed in a lower index than 'b'

}
else return 0 // null -> they are equal, so leave in place

It should be noted that array.sort will always expect ‘a’ to be the first argument, and ‘b’ the second. So if you wanted a reverse sort, you could do

if (campareA < campareB) {

        return 1; // true -> 'a' should be placed in a higher index than 'b'

}

if (campareA > campareB) {

   return -1; // false -> 'a' should be placed in a lower index than 'b'

}
else return 0 // null -> they are equal, so leave in place

So the callback function that you provide to the sort argument tells the sort function how to sort the values in the array.

To answer your first ques , why to use -1, 1 and 0:
You use this values as return values to the sort function according to some given condition inside the function. This return value enables the sort function to properly sort the array.
In case of number or string the sort function can just sort it out by itself without the callback function, but for complex structures like objects you need to tell the function how exactly to sort and using which properties of the object. Thus returning values of 1, -1 or 0 enables the sort function to check if values are equal or which one is greater.

Secondly to execute the code:
Simply call the function like:

array.sort(function() {
   //code returning 1 , -1 or 0
});