Steven
Steven

Reputation: 401

Sorting using Javascript

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();
}

Upvotes: 2

Views: 220

Answers (1)

thefourtheye
thefourtheye

Reputation: 239473

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

  1. negative if first value is lesser than the second

  2. positive if the second value is greater than the first

  3. 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 } ]

Upvotes: 5

Related Questions