What does the return type 1, -1, and 0 do in a sort function?

advertisements

Here is the working piece of code given as an answer to the question for implementing sorting of objects and it is working perfectly fine. As I am new to JavaScript I'm not understanding what exactly the return type does. Can anyone explain please?

var people= [
     {
        "f_name": "john",
        "l_name": "doe",
        "sequence": "0",
        "title" : "president",
        "url" : "google.com",
        "color" : "333333",
    }
    // etc
];

function sortResults(prop, asc) {
    people = people.sort(function(a, b) {
        if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
        else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
    });
    showResults();
}

Argument 'prop' is the propertyName based on which sorting needs to be done, and asc is a boolean type which sorts in asc order if true or desc order if false.


It's Array.sort and has nothing to do with jQuery. Remember that jQuery is yet another library developed in javascript.

The MDN explains this already:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  1. If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

  3. If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

  4. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined

It's not mandatory to return only -1 or 1.