简体   繁体   中英

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

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 , ie 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 (eg 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 .

Well, it returns how 2 elements should be ordered relative to one another.

If it's -1 then it means that the elements should be swapped because they are in inverse order. So if the

If it's 1 it means that the elements are in the right order.

If it's 0 then it means that the elements are either equal or have equal positions so it doesn't matter in which order they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM