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:
If
compareFunction(a, b)
is less than0
, sorta
to a lower index thanb
, iea
comes first.If
compareFunction(a, b)
returns0
, leavea
andb
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.If
compareFunction(a, b)
is greater than 0, sortb
to a lower index thana
.
compareFunction(a, b)
must always return the same value when given a specific pair of elementsa
andb
as its two arguments. If inconsistent results are returned then the sort order isundefined
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.