I am trying to get my page to sort by event_id. Currently the way my code is written I will get the first record for example will be 6719 then 6700, 6701, 6702 etc. It should go like this 6719, 6718, 6716, and so on. Let me know how I need to rewrite this code to do that sorting just straight descending order.
function() {
this.blockEvent();
this.sort(function(a, b) {
return a.event_id < b.event_id ? 1 : 1
});
this.unblockEvent();
}
-
1What the 4th line of codes doing? return 1 or 1?nightire– nightire2014年03月25日 15:21:07 +00:00Commented Mar 25, 2014 at 15:21
1 Answer 1
If the event_ids are equal, you need to return 0. Instead of returning three different values depends on the values, you can simply return their differences, if they both are numbers
this.sort(function(a, b) {
return b.event_id - a.event_id;
});
This works because, JavaScript's Array.prototype.sort function accepts a function which returns a number as output, which should be
negative if first value is lesser than the second
positive if the second value is greater than the first
zero, if both of them are the same.
For example, if you have the list of objects, like this
var objects = [{
"event_id": 6701
}, {
"event_id": 6719
}, {
"event_id": 6710
}, {
"event_id": 6703
}];
You can sort them in ascending order, like this
console.log(objects.sort(function(a, b) {
return a.event_id - b.event_id;
}))
Output
[ { event_id: 6701 },
{ event_id: 6703 },
{ event_id: 6710 },
{ event_id: 6719 } ]
If you want to sort them in the descending order, you can simply reverse the numbers being compared
console.log(objects.sort(function(a, b) {
return b.event_id - a.event_id;
}));
Output
[ { event_id: 6719 },
{ event_id: 6710 },
{ event_id: 6703 },
{ event_id: 6701 } ]